gpt4 book ai didi

javascript - 发送回函数时如何接收 res.send(req.body)

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:24 25 4
gpt4 key购买 nike

我正在尝试将 POST 请求路由上的 req.body 发送回执行 POST 请求的函数。

req.body 是这样的 { username: 'aa', password: 'ss' }

我正在使用一个函数来发布,并且在发布后想要处理响应。

使用 res.sendStatus(200) 或 res.sendStatus(401) 我可以像这样访问它

post('/login', { username, password })
.then(({ status }) => {
if (status === 200) {alert('login success'); window.location.href = "/about"}
else alert('login failed')
})

当使用 res.send(req.body)res.json(req.body) 进行响应时,如何使用 then() 访问用户名

我尝试了.then(({ username }) => {alert(username)})并得到了未定义的错误

最佳答案

如果您使用 fetch API,当您在响应对象上调用 json() 时,您将获得响应 json。

post('/login', { username, password })
.then(({ status, json }) => {
const responseJSON = json();
const { username } = responseJSON; // all your data will be in this object
if (status === 200) {alert('login success'); window.location.href = "/about"}
else alert('login failed')
})

如果您使用的是 axios,您的响应 json 将会位于 data 对象中。

post('/login', { username, password })
.then(({ status, data }) => {
const responseJSON = data;
const { username } = responseJSON; // all your data will be in this object
if (status === 200) {alert('login success'); window.location.href = "/about"}
else alert('login failed')
})

关于javascript - 发送回函数时如何接收 res.send(req.body),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53808255/

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