如何修复JavaScript未向服务器发送任何req.body的问题

huangapple go评论77阅读模式
英文:

How to fix javascript not sending any req.body to server

问题

我没收到任何 req.body 参数。在 Postman 中使用 POST 请求时一切都正常。

代码:

async function postRequest(url, data){
    const response = await axios.post(url, data, {
        headers: {
            "Content-Type": "application/json"
        }
    })
    return response.data
}

服务器端:

app.use(bodyParser.urlencoded({extended: true}))

在添加任何 app.get 函数之前使用这个。

任何帮助将不胜感激。

FYI,我使用 ReactJS。

英文:

I m not getting any req.body parameters. Its working perfectly fine while posting with postman
Code:


async function postRequest(url, data){

    const response = await axios.post(url, data, {
        headers: {
            "Content-Type": "application/json"
        }
    })
    return response.data
  }

server side:

    app.use(bodyParser.urlencoded({extended: true}))

I use this before adding any app.get functions.

Any help would be appreciated.
FYI I use reactjs

答案1

得分: 0

你将内容类型设置为 JSON,但你的服务器期望的是 application/x-www-form-urlencoded。你应该将内容类型设置为 application/x-www-form-urlencoded

async function postRequest(url, data) {

    const response = await axios.post(url, data, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    });
    return response.data;
}
英文:

You set the content type to json but your server is expecting application/x-www-form-urlencoded. You should set the content type to application/x-www-form-urlencoded

async function postRequest(url, data){

    const response = await axios.post(url, data, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    })
    return response.data
}

答案2

得分: 0

尝试使用

app.use(bodyParser.json())
英文:

Try to use
'''
app.use(bodyParser.json())
'''

huangapple
  • 本文由 发表于 2023年2月16日 10:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467357.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定