gpt4 book ai didi

javascript - 在 req.body 中接收两个对象

转载 作者:行者123 更新时间:2023-11-29 20:30:50 27 4
gpt4 key购买 nike

我正在接收来自 Unity 应用程序的 POST 请求,该请求以 x-form-encoded 格式发送到我的 NodeJs 网络服务器中。

我使用 app.use(bodyParser.urlencoded({ extended: true})) 来解析内容。但是 req.body 返回两个对象,问题是我无法访问单个属性的属性,因为它们既没有包装在数组或对象中。

关于console.log(req.body)

我得到以下结果

{ sessionId: '5ujgp6vwk1pivth4', gameId: '1', level: '0', score: '0' }            

{ sessionId: '5ujgp6vwk1pivth4', gameId: '2', level: '0', score: '0' }

我想知道这是哪种类型的数据类型以及我将如何访问特定属性,假设我这样做了console.log(req.body.sessionId) ,我明白了

5ujgp6vwk1pivth4

5ujgp6vwk1pivth4

即使我尝试将它放入数组中,我仍然会得到相同的结果。

我正在尝试将这些对象提取到一个数组中,以便我可以更轻松地访问它们。

Express 路由的脚本:

const express = require('express')
const path = require('path')
const hbs = require('hbs')
const bodyParser = require('body-parser')
const viewsRouter = require('./routers/views')
const apiRouter = require('./routers/api')
const cookieParser = require('cookie-parser')
require ('./db/mongoose')

const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true}))
app.use(cookieParser())
const publicDirectoryPath = path.join(__dirname,'../public')
app.use(express.static(publicDirectoryPath))
const viewsPath = path.join(__dirname,'../templates/views')
const partialsPath = path.join(__dirname,'../templates/partials')

hbs.registerPartials(partialsPath)
hbs.registerHelper('ifCond', function(v1, v2, options) {
if(v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
hbs.registerHelper("math", function(lvalue, operator, rvalue, options) {
lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);

return {
"+": lvalue + rvalue,
"-": lvalue - rvalue,
"*": lvalue * rvalue,
"/": lvalue / rvalue,
"%": lvalue % rvalue
}[operator];
});
app.use(viewsRouter)
app.use(apiRouter)
// For any of the un-handled routes
app.get('*',(req,res)=>{
res.render('error')
})

//Setting up the CORS functionality in Express for Making AJAX calls
app.use(function(req, res, next) {

res.header("Access-Control-Allow-Origin", "*");

res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

next();

});

app.set('views',viewsPath)
app.set('view engine','hbs')


app.listen(80,()=>{
console.log('Server Started on Port 80')
})

负责特定 POST 的路由是

apiRouter.post('/api/updateScore/',async(req,res)=>{ 
console.log(req.body)
})

客户端脚本是:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using UnityEngine.SceneManagement;
using System.Text;

public class ScoreSender : MonoBehaviour {

public Authentication authentication;
public static readonly string scoreUrl = "https://eyenet.pythonanywhere.com/scores/";
public static ScoreSender instance;
public string Address = "127.0.0.1:8000";
// Use this for initialization
void Start () {
instance = this;
}

// Update is called once per frame
void Update () {

}

public void sendScore(int gameId, int level)
{

}

public void sendScore(string gameId, int level, int score)
{
string loginURL = Address+ "/api/updateScore/";

WWWForm form = new WWWForm();
form.AddField( "sessionId", authentication.session );
Dictionary<string, string> headers = form.headers;
byte[] rawData = form.data;

WWW www = new WWW(loginURL, rawData, headers);

}
// StartCoroutine(WaitForRequest(www));



public void saveScore(string gameId, int nextlevel, int score)
{

// get session id
string sessionCode = authentication.session;

// get score array
int noOfGames = PlayerPrefs.GetInt("totalGames",0);

// get or create score, level, nextlevel arrays
int gid = int.Parse(gameId);


//
int[] scoreArray = PlayerPrefsX.GetIntArray(sessionCode+"scores",0,noOfGames+1);
int[] nextLevelsArray = PlayerPrefsX.GetIntArray(sessionCode+"nextLevels",0,noOfGames+1);

nextLevelsArray[gid] = nextlevel;
scoreArray[gid] = score;

PlayerPrefsX.SetIntArray(sessionCode+"scores",scoreArray);
PlayerPrefsX.SetIntArray(sessionCode+"nextLevels",nextLevelsArray);

PlayerPrefsX.SetIntArray("gameLevels",nextLevelsArray);
Debug.Log("saved score and nextLevels offline");
}

//for sending score to the cloud


public void uploadScore()
{
//testing
//StartCoroutine(scoreSend(authentication.session,"1",45,34));
syncScore(authentication.session);

}


//for online sessions only
void syncScore(string sessionId)
{
Debug.Log("We are syncing the score for this session");

int noOfGames = PlayerPrefs.GetInt("totalGames",0);
int[] currentGamePlays = PlayerPrefsX.GetIntArray(sessionId+"currentGamePlays",0,noOfGames);
int[] scoreArray = PlayerPrefsX.GetIntArray(sessionId+"scores",0,noOfGames+1);
int[] nextLevelsArray = PlayerPrefsX.GetIntArray(sessionId+"nextLevels",0,noOfGames+1);


for(int i=0;i<noOfGames+1;i++)
{
if(currentGamePlays[i]==1) //if the game is played in this session
{
StartCoroutine( scoreSend(sessionId,""+i,nextLevelsArray[i],scoreArray[i]));
Debug.Log("score:"+scoreArray[i]);
Debug.Log("level:"+nextLevelsArray[i]);
}
}
}


public int noOfScores=0;

public void syncOfflineScore(int num,string actualId)
{
string sessionId = "offlineSession"+num;

int noOfGames = PlayerPrefs.GetInt("totalGames",0);
int[] currentGamePlays = PlayerPrefsX.GetIntArray(sessionId+"currentGamePlays",0,noOfGames+1);
int[] scoreArray = PlayerPrefsX.GetIntArray(sessionId+"scores",0,noOfGames+1);
int[] nextLevelsArray = PlayerPrefsX.GetIntArray(sessionId+"nextLevels",0,noOfGames+1);


for(int i=0;i<noOfGames+1;i++)
{
if(currentGamePlays[i]==1) //if the game is played in this session
{
noOfScores++;
}
}


for(int i=0;i<noOfGames+1;i++)
{
if(currentGamePlays[i]==1) //if the game is played in this session
{
StartCoroutine( offlineScoreSend(actualId,""+i,nextLevelsArray[i],scoreArray[i]));
Debug.Log("score:"+scoreArray[i]);
Debug.Log("level:"+nextLevelsArray[i]);
}
}


}







//working fine
IEnumerator scoreSend(string sessionId,string gameId,int nextlevel, int score)
{
string scoreUrl = authentication.Address+ "/api/updateScore/";

WWWForm form = new WWWForm();

form.AddField( "sessionId", sessionId );
form.AddField( "gameId", gameId );
form.AddField( "level", nextlevel);
form.AddField( "score", score);

Dictionary<string, string> headers = form.headers;
//Dictionary<string, string> headers = new Dictionary<string, string>();
//headers.Add("Content-Type", "application/json");
byte[] rawData = form.data;

WWW www = new WWW(scoreUrl, rawData, headers);
WWW data =www;

yield return data;
if(data.error!=null)
{
Debug.Log (data.error);

if(data.error == "Cannot connect to destination host")
{

}

}
else
{
Debug.Log(data.text);
ServerResponse res = JsonUtility.FromJson<ServerResponse>(data.text);
if(res.status==0)
{
Debug.Log("Updated score");

}
else
{
Debug.Log("Got an error");
}
}
}


//test it
IEnumerator offlineScoreSend(string sessionId,string gameId,int nextlevel, int score)
{
string scoreUrl = authentication.Address+ "/api/updateScore/";

WWWForm form = new WWWForm();

form.AddField( "sessionId", sessionId );
form.AddField( "gameId", gameId );
form.AddField( "level", nextlevel);
form.AddField( "score", score);

Dictionary<string, string> headers = form.headers;
byte[] rawData = form.data;

WWW www = new WWW(scoreUrl, rawData, headers);
WWW data =www;

yield return data;
if(data.error!=null)
{
Debug.Log (data.error);

if(data.error == "Cannot connect to destination host")
{

}

}
else
{
Debug.Log(data.text);
ServerResponse res = JsonUtility.FromJson<ServerResponse>(data.text);
if(res.status==0)
{
Debug.Log("Updated score");
noOfScores--;
if(noOfScores==0)
{
authentication.syncOfflineSessionsDataComplete();
}
}
else
{
Debug.Log("Got an error");
}
}
}





}

最佳答案

不幸的是,正在发生的事情与您认为正在发生的事情不同,这里没有足够的信息来弄清楚到底发生了什么。你说 req.body 返回了两个对象,但它们没有被包裹在数组或另一个对象中,这根本不可能。

根据可用信息,我最好的猜测是 bodyParser 正在正常工作,但是无论您用来发送请求的客户端应用程序都在发送两个请求,而您认为它只发送一个请求,所以当您记录它时您看到两个对象并假设它们来自对 console.log 的一次调用,但事实并非如此。

为了确认这一点,我可能会将类似这样的内容粘贴到文件底部,然后使用它来记录而不是直接使用 console.log。这将证明这是来自两次不同的路由调用的两个不同的日志条目。

let counter = 0;
function logWithCounter( ...msg ) {
console.log( counter++, ...msg );
}

关于javascript - 在 req.body 中接收两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58368086/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com