首页 > 解决方案 > 我需要从 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;
        });

标签: jsonnode.jshttpvue.js

解决方案


您过度使用请求选项。

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( ... )

推荐阅读