简体   繁体   English

为什么当参数作为 object 发送时,节点服务器不读取反应中的 axios 帖子?

[英]Why axios post in react is not read by the node server, when params are sent as object?

The params are sent.参数已发送。 I can see the endpoint triggered, and dev tools display them.我可以看到端点被触发,并且开发工具会显示它们。 However, query params are not received by the server or interpreted incorrectly.但是,服务器未接收到查询参数或解释不正确。 Simple axios.post :简单axios.post

async function login(username, password) {
    return await axios.post(LOGIN_URL, {
            username,
            password
        },
    );
}

This situation is completely different if I'm just writing the query by hand, everything is received:如果我只是手动编写查询,这种情况就完全不同了,一切都收到了:

axios.post(LOGIN_URL + `?username=${username}&password:${password}`);

I want to use my bodyParser in educational purposes.我想将我的 bodyParser 用于教育目的。 Interpretation is as simple as possible with just 4 logs:解释尽可能简单,只需 4 个日志:

function bodyParser (req, res, next) {
    const body = url.parse(req.url).query;

    console.log(req.url); // /auth
    console.log(req.query); // {}
    console.log(req.body); // undefined
    console.log(req.params); // {}

    res.body = body;
    next();
}

The app:应用程序:

import express from 'express';

import cors from 'cors';
import bodyParser from './middlewares';

import auth from "./routes/auth.route";

const app = express();

app.use('/', cors());
app.use('/', bodyParser);

app.use('/auth', auth);

export default app;
async function login(username, password) {
return await axios.post(LOGIN_URL, {
        username,
        password
    },
);
}

That's sending username and password in the req.body.那就是在 req.body 中发送用户名和密码。 So in Node, you need to be checking req.body所以在 Node 中,你需要检查 req.body

A Url like so:像这样的 Url:

http://someurl.com/api?username=a&password=b

You pick those variables up in req.query.您在 req.query 中选择这些变量。

A Url like so:像这样的 Url:

http://someurl.com/api/people/some_id_here

You pick that ID up in req.params.您在 req.params 中选择该 ID。

I believe there is an issue with how you're calling axios.post(...) .我相信您如何调用axios.post(...)存在问题。 Assuming that when you call axios this way and it works:假设当您以这种方式调用axios并且它可以工作时:

axios.post(LOGIN_URL + `?username=${username}&password:${password}`); 

The username and password variables passed to axios.post(LOGIN_URL, {username, password}) are string variables.传递给axios.post(LOGIN_URL, {username, password})usernamepassword变量是字符串变量。 Therefore, you forgot to key the values like so,因此,您忘记像这样键入值,

async function login(username, password) {
    return await axios.post(LOGIN_URL, {
            'username': username,
            'password': password
        },
    );
}

Now in your bodyParser function, you should be able to access these variables passed in via req.params.username and req.params.password .现在在您的bodyParser function 中,您应该能够访问通过req.params.usernamereq.params.password传入的这些变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM