我想在基于 nodejs 服务器的客户端使用 ajax 获取我发布的 JSON 对象的内容。
如果我在客户端有如下代码:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('#form').click(function(e){
e.preventDefault();
hellodata = {
id : '1234',
content: 'hello'
};
$.ajax({
url : "http://localhost:3000/savedata",
type: "POST",
data : hellodata,
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
});
</script>
如何获取服务端的参数id和content?
server.post("/savedata", function(req, res){
//I get here after doing the ajax post and I want to show here the content of hellodata json
});
谢谢!
最佳答案
要在您的POST
请求中读取JSON
,您应该使用body-parser
:
npm install --save body-parser
然后添加到你的服务器端:
var bodyParser = require('body-parser');
// parse application/json
server.use(bodyParser.json());
server.post("/savedata", function(req, res){
console.log(req.body);
});
您还必须使用以下内容更新您的 ajax 请求:
contentType: "application/json",
data: JSON.stringify(hellodata),
关于javascript - 在 NodeJS api 服务器中从客户端获取 JSON 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29882601/