Javascript 在Express中接收Jquery POST数据
编辑有关修复方法,请参见下面接受的答案。我还必须从我的POST请求中删除Javascript 在Express中接收Jquery POST数据,javascript,jquery,node.js,express,post,Javascript,Jquery,Node.js,Express,Post,编辑有关修复方法,请参见下面接受的答案。我还必须从我的POST请求中删除contentType:'appliction/json', 我试图向Node.js/Express发送一个字符串,但是req.body在服务器端没有定义 客户端jQuery: $.post({ traditional: true, url: '/matches', contentType: 'appliction/json', data: viewedProf
contentType:'appliction/json',
我试图向Node.js/Express发送一个字符串,但是req.body
在服务器端没有定义
客户端jQuery:
$.post({
traditional: true,
url: '/matches',
contentType: 'appliction/json',
data: viewedProfiles,
dataType: 'json',
success: function(response){
快递:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post('/matches', isLoggedIn, function(req, res){
console.log(req.body) // this is undefined
var loadedProfiles = []
loadedProfiles.push(req.body.viewedProfiles)
console.log('loadedProfiles')
console.log(loadedProfiles)
我试过:
- 未指定“数据类型”
- 设置
data:JSON.stringify(viewProfiles)
- 在客户机上将字符串拆分为数组,然后让jQuery将其字符串化
- 寻找req.params而不是req.body(抓住吸管)
谢谢。您的服务器端代码看起来不错,但您需要使用
$.ajax()
而不是$.post()
函数,因为$.post()
函数将数据发送到url(url编码)。所以您的JQuery代码应该是
$.ajax({
url: '/matches',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"viewedProfiles": viewedProfiles}),
success: function(response){
我希望这将帮助您我已经配置了完全相同的设置。代码如下:
var profiles = { 'data' : 'hello' };
$.post({
traditional: true,
url: '/matches',
contentType: 'application/json',
data: JSON.stringify( profiles ),
dataType: 'json',
success: function(response){ console.log( response ); }
} );
我的nodejs引擎:
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.post( '/matches' , function(req, res){
console.log(req.body) // this outputs: { data: 'hello' }
} );
顺便说一句,您的contentType有一个输入错误,即“application/json”您的页面中是否运行了
connect
中间件?我没有,但我在应用程序的其他地方成功运行了jQuery数据帖子。是的,这真的帮助了我!我还必须删除行contentType:'appliction/json',
,然后它才能工作。