尝试复制一个简单的例子,但仍无法解析json post请求, 想法? 看着borwser(firefox)网络选项卡,我看到了json params的请求。 但是服务器日志是空的。
客户端
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
服务器
//require the express nodejs module
var express = require('express'),
//set an instance of exress
app = express(),
//require the body-parser nodejs module
bodyParser = require('body-parser'),
//require the path nodejs module
path = require("path");
//support parsing of application/json type post data
app.use(bodyParser.json());
app.post('/', function(req, res){
res.setHeader('Content-Type', 'application/json');
console.log(req.body);
res.send("done");
});
//Start listen on port
const port = 8080;
app.listen(port);
console.log("Node js listen on port " + port + "...");
答案 0 :(得分:0)
您没有使用AJAX请求设置Content-Type标头。请更改为以下内容。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var man = {
name:'name',
fam:'familiy'
};
var xhttp = new XMLHttpRequest();
var url = "http://localhost:8080/";
xhttp.open("post", url, true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(man));
</script>
<title>Json Test</title>
</head>
<body>
Json Test
</body>
</html>
答案 1 :(得分:0)
以及.... 我想我也忘记了这些(现在正在工作)
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, **POST**, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});