gpt4 book ai didi

javascript - 在 Node.JS 中读取 AJAX 发布变量(使用 Express)

转载 作者:IT老高 更新时间:2023-10-28 23:19:29 24 4
gpt4 key购买 nike

我正在尝试获取我为 Node 应用程序中的 ajax 帖子发送的值。使用 this post作为指导,到目前为止我有这个:

在 Node 中:

 var express = require('express');
var app = express();

var db = require('./db');

app.get('/sender', function(req, res) {
res.sendfile('public/send.html');
});

app.post('/send_save', function(req, res) {
console.log(req.body.id)
console.log(req.body.title);
console.log(req.body.content);
res.contentType('json');
res.send({ some: JSON.stringify({response:'json'}) });
});

app.listen(3000);

在 AJAX 方面:

$('#submit').click(function() {
alert('clicked')
console.log($('#guid').val())
console.log($('#page_title').val())
console.log($('#page-content').val())
$.ajax({
url: "/send_save",
type: "POST",
dataType: "json",
data: {
id: $('#guid').val(),
title: $('#page_title').val(),
content: $('#page-content').val()
},
contentType: "application/json",
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},

success: function(data) {
console.log(data);
console.log('process sucess');
},

error: function() {
console.log('process error');
},
});
})

这个问题是我不能 req.body.id(以及任何其他值,如标题或内容),我在 Node 中收到此错误:

 TypeError: Cannot read property 'id' of undefined

如果我将这些调用注释掉,则 ajax 是成功的。我搞不清楚了。我是不是忘记了什么?

最佳答案

您拥有的 req 对象没有 body 属性。看看http://expressjs.com/api.html#req.body :

This property is an object containing the parsed request body. This feature is provided by the bodyParser() middleware, though other body parsing middleware may follow this convention as well. This property defaults to {} when bodyParser() is used.

因此,您需要像这样将 bodyParser 中间件添加到您的 express webapp:

var app = express();
app.use(express.bodyParser());

关于javascript - 在 Node.JS 中读取 AJAX 发布变量(使用 Express),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15042245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com