以下是console.log(payload)
的数据示例:
对象{title:“test post”,消息:“some message”,image:“cat.jpg”}
然而,这是我的mongo系列中出现的内容:
{
"_id": "5684609f8d6ff91e159cef6d",
"created_at": "2015-12-30T22:54:23.266Z",
"updated_at": "2015-12-30T22:54:23.266Z",
"__v": 0
}
以下是代码:
console.log(payload); // what this returns is posted above!
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost:3000/api/v1/posts', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send(payload);
有人能帮助我吗?
以下是来自server.js的相关代码:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/fluxible-posts');
var Post = require('./database/postModel');
// routes
var router = express.Router();
server.use('/api/v1/', router);
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
// test route
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
router.route('/posts')
.post(function(req,res) {
var post = new Post();
post.title = req.body.title;
post.message = req.body.message;
post.image = req.body.image;
post.save(function(err) {
if(err) {
res.send(err);
}
res.json({ message : 'New post created' });
});
})
.get(function(req, res) {
Post.find(function(err, posts) {
if (err)
res.send(err);
res.json(posts);
});
});
router.route('/posts/:post_id')
// get the post with that id
.get(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err)
res.send(err);
res.json(post);
});
})
// update the post with this id
.put(function(req, res) {
Post.findById(req.params.post_id, function(err, post) {
if (err)
res.send(err);
post.name = req.body.name;
post.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Post updated!' });
});
});
})
// delete the post with this id
.delete(function(req, res) {
Post.remove({
_id: req.params.post_id
}, function(err, post) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
答案 0 :(得分:1)
如果您添加request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
,您应该发送不在对象中的有效负载,但是作为POST数据字符串,如
title=test%20post&message=some%20message&image=cat.jpg
您可以使用Query-string encoding of a Javascript Object
中的序列化功能<强>更新强>
正如我所见,您没有将POST数据解析器中间件添加到路由器中,因此您的req.body
未定义。对于Content-Type: application/x-www-form-urlencoded
,您应该使用body-parser
模块。
您可以使用npm install body-parser
进行安装,并将服务器代码更改为
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.urlencoded({ extended: true }));
server.use('/api/v1/', router);
我的评论的第一部分仍然有效。
更新2:
或者,您可以使用Content-type: application/json
。在这种情况下,您需要更新您的客户端代码,如下所示:
var payload = {test: "data"}
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost:3005/api/v1/posts', true);
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify(payload));
服务器端:
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.json());
server.use('/api/v1/', router);
答案 1 :(得分:1)
尝试以下代码
var request = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log("success : " + request.responseText);
} else {
//This would print if something goes wrong along with the error message
console.log("other status : " + request.status + " : " + request.responseText);
}
};
request.open('POST', 'http://localhost:3000/api/v1/posts', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//We need to serialize payload before sending it
request.send(JSON.stringify(payload));
您可以使用开发者工具下的Chrome网络标签来监控发送的网络请求。在那里,您将能够看到请求的主体是否已发送,或者标头是否已按设置发送以及响应是什么。
请参阅下面的图片