gpt4 book ai didi

Javascript 客户端在 POST 请求中发送正文,但 Node.js 服务器将其获取为空

转载 作者:行者123 更新时间:2023-12-03 04:21:14 26 4
gpt4 key购买 nike

我希望能够在我的服务器控制台中看到 {"content":"test data"} (它应该作为 POST 请求的正文从客户端发送),但我得到:

Listening to 8080...
I'm in myServer.use
POST request received
req.params: {}
req.body: undefined
req.query: {}

这是我的客户端,它只是一个启动他的 onclick 函数的按钮:

<!DOCTYPE html>
<html>
<head>
<title>REST WebClient</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<p>This web is a REST client.</p>

<script type="text/javascript">
function POSTpressed(){
//Making the request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", 'http://127.0.0.1:8080/v0/prueba/', true ); // false for synchronous request
xmlHttp.send( {"content":"test data"} );
}
</script>

<input type="button" onclick="POSTpressed();" id="POSTbutton" value="POST"/>

</body>
</html>

这里是服务器。如果有人尝试复制它,则需要安装“express”库。

var express = require('express');
var myServer = express();

//stuff for server to going on
myServer.use(function(req, res, next){
console.log("I'm in myServer.use");
res.set('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*'); //general access
next();
});

//function which handles POST requests
myServer.post('/v0/prueba/', function(req, res){
console.log('POST request received');
//trying to see the sent body
console.log("req.params: "+JSON.stringify(req.params));
console.log("req.body: "+ req.body); //req.body.content would throw error: no content in undefined
console.log("req.query: "+ JSON.stringify(req.query));

res.send(null);

});//myServer.post

myServer.listen(8080);
console.log('Listening to 8080...');

最佳答案

在服务器端,您需要添加 body-parser 中间件来解析正文:

var bodyParser = require('body-parser')

:

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

关于Javascript 客户端在 POST 请求中发送正文,但 Node.js 服务器将其获取为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43936065/

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