json - 我需要从 Vue(SPA)发送一个 json obj 到节点(服务器)
问题描述
我正在尝试使用 Axion 将表单从 vue 应用程序发送到节点服务器。但我无法在服务器端的请求中得到任何东西。我在 vue 中有用户名和密码,但我无法将其发送到服务器进行处理,另外我可以得到 x-www-form-urlencoded 类型的 Postman 响应并查看服务器是否正常工作。我尝试更改“内容类型”的类型,但仍然没有得到任何东西
服务器端。
服务器:
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
内容类型是(以及几乎所有其他现有的 HTTP 库)的默认值,不需要axios.post()
任何JSON.stringify()
东西。毕竟,您不想将 JSON 发送到服务器,而是发送表单编码的数据。
直接发布一个对象:
return axios.post('http://127.0.0.1:3000/user/login', {
nationalID: username,
password: password
})
.then( ... )
推荐阅读
- postgresql - 如何优化搜索多对多表的查询
- c# - 始终同时运行 3 个任务
- laravel - Laravel CSRF 保护是否提供 100% 的安全性?
- python - 使用 SLL 返回对象地址而不是实际值的堆栈查看方法
- java - Flutter/Dart - FlutterFirebaseMessagingPlugin.java - 构建失败并出现异常“错误:找不到符号”
- powershell - 抑制 get-azureaddomain 的输出
- c++ - 为什么 C++ 中 std::string 的复制方法在该程序中表现出奇怪的行为?
- django - Django 连接到托管在 Amazon EC2 上的 Redis 服务器
- javascript - javascript - scrollToView(false) 不工作
- javascript - 如何以角度读取css变量?