node.js表示:无法获取jquery ajax发布的数据
在客户端,我使用jquery发布数据:
var data = { 'city': 'england' } $.ajax({ 'type': 'post', 'url': 'http://127.0.0.1:8000/', 'data': data, 'dataType': 'json', 'success': function () { console.log('success'); } })
在我的server.js中,我尝试捕获该数据:
var express = require('express'); var app = express.createServer(); app.configure(function () { app.use(express.static(__dirname + '/static')); app.use(express.bodyParser()); }) app.get('/', function(req, res){ res.send('Hello World'); }); app.post('/', function(req, res){ console.log(req.body); res.send(req.body); }); app.listen(8000);
该post可以成功,它返回200状态,但我不能login发布数据,它什么都没有返回,而terminal日志undefined
。
为什么? 我怎么解决这个问题?
您没有正确发送数据。
$.ajax({ type: 'POST', data: JSON.stringify(data), contentType: 'application/json', url: '/endpoint' });
用jQuery,使用
的contentType: '应用/ JSON'
发送JSON数据。