gpt4 book ai didi

json - 我需要从 Vue(SPA) 发送一个 json 对象到 Node (服务器)

转载 作者:可可西里 更新时间:2023-11-01 17:04:47 26 4
gpt4 key购买 nike

我正在尝试使用 Axion 将表单从 vue 应用程序发送到 Node 服务器。但我无法在服务器端的请求中得到任何东西。我在 vue 中有用户名和密码,但我无法将其发送到服务器进行处理,而且我可以通过 Postman 获得 x-www-form-urlencoded 类型的响应并查看服务器是否正常工作。我尝试更改“Content-Type”的类型,但仍然没有在


服务器端。

服务器:

    router.options('/login',function(request, response, next) {
console.log(request.body);
var login = methods.login(request.body.nationalID, request.body.password)
.then((result) => {
response.status(200).send({
success: true,
roles: result.roles,
token: result.token
})
}).catch((err) => {
response.status(err.code).send({
success: false,
message: err.message
})
})
});

router.post('/login',function(request, response, next) {

console.log(request.body);
var login = methods.login(request.body.nationalID, request.body.password)
.then((result) => {
response.status(200).send({
success: true,
roles: result.roles,
token: result.token
})
}).catch((err) => {
response.status(err.code).send({
success: false,
message: err.message
})
})
});

和服务器配置:

app.use(bodyParser.json()); // <--- Here
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

客户端:

const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({nationalID:username, password:password})
};

return axios.post('http://127.0.0.1:3000/user/login', requestOptions)
.then(handleResponse)
.then(user => {
// login successful if there's a jwt token in the response
if (user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('user', JSON.stringify(user));
}

return user;
});

最佳答案

您过度使用了请求选项。

x-www-form-urlencoded 内容类型是 axios.post() 的默认值(以及几乎所有其他现有的 HTTP 库),并且有不需要 JSON.stringify() 任何东西。毕竟,您不想向服务器发送 JSON,而是发送表单编码数据。

直接发布一个对象即可:

return axios.post('http://127.0.0.1:3000/user/login', {
nationalID: username,
password: password
})
.then( ... )

关于json - 我需要从 Vue(SPA) 发送一个 json 对象到 Node (服务器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52675584/

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