gpt4 book ai didi

javascript - 在 Express 中接收 Jquery POST 数据

转载 作者:搜寻专家 更新时间:2023-11-01 00:30:02 25 4
gpt4 key购买 nike

编辑 请参阅下面已接受的答案以了解修复方法。我还必须从我的 POST 请求中删除行 contentType: 'appliction/json',

我正在尝试向 Node.js/Express 发送一个字符串,但是 req.body 是未定义的服务器端。

客户端 jQuery:

$.post({
traditional: true,
url: '/matches',
contentType: 'appliction/json',
data: viewedProfiles,
dataType: 'json',
success: function(response){

express :

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)

我试过:

  • 未指定“数据类型”
  • 设置数据:JSON.stringify(viewProfiles)
  • 在客户端将字符串拆分成一个数组,然后让 jQuery 将其字符串化
  • 寻找 req.params 而不是 req.body(捕获救命稻草)

我可以在开发工具中看到 XHR 请求,它包含我期望的字符串。

我在将数据发送到 Express 时错过了什么非常明显的事情?

谢谢。

最佳答案

您的服务器端代码看起来不错,但您需要使用 $.ajax() 而不是 $.post() 函数,因为 $.post() 函数将数据发送到 url(使用 url 编码)。所以你的 JQuery 代码将是

$.ajax({
url: '/matches',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({"viewedProfiles": viewedProfiles}),
success: function(response){

希望对你有帮助

关于javascript - 在 Express 中接收 Jquery POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40001564/

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