gpt4 book ai didi

node.js - ajax调用无法将参数传递给nodejs应用程序

转载 作者:太空宇宙 更新时间:2023-11-04 00:18:35 26 4
gpt4 key购买 nike

我通过下面的代码进行ajax调用,并期望看到传递给nodejs应用程序的参数,但它总是空的

@action postData() {
$.ajax({
url:"http://localhost:8080/sendMail",
ContentType:'application/json',
dataType:'json',
type:'post',
data:JSON.stringify({'message':'helloworld'}),
success:(result) =>{
..
})

如果我在 postman 中发出一个发布请求(向正文添加原始字符串 json 参数;{'message':'helloworld'}),它会很好地传递,并且我会看到它已记录。那么我在reactjsapp 中使用的ajax 调用有什么问题吗?

编辑:它看起来在浏览器中传递的所有参数都很好,但不知何故nodejs无法获取它们。 enter image description here

最佳答案

由于 POST 数据是在 HTTP 正文中发送的,因此您需要解析其中的 JSON 才能获取它。假设您在服务器端使用express.js,您可以使用 body-parser为此:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

关于node.js - ajax调用无法将参数传递给nodejs应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45531852/

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