Axios post doesn't receive answer (ReactJS)

2019-08-16 16:48发布

问题:

I need to submit a form. It currently works if I do it in the HTML form, but I really need to make some stuff after so I need to do it in react. So I'm using axios.

However, using axios I don't get a response back. Also there's something strange, because although I'm doing a post request, the data appears as a query string on the browser... Not sure if that's the normal behaviour.

Here's my code, on the server side:

app.post("/auth/register", async function(req, res, next) {
    // some code
    // my responses are like res.json("/signup/success");
}

on the client side:

onSubmit(event) {
    axios({
        method: "post",
        url: "/auth/register",
        data: {
            username: this.state.username,
            password: this.state.password,
            accountName: this.state.accountName
        },
        withCredentials: true
    }).then(result => {
        console.log(result);
    });
}

I'm running a server on port 5000 using express, and I used create-react-app to run a server on port 3000. To manage authentication, passport.js.

I use http-proxy-middleware to proxy some endpoints to the express server.

After submitting the form I get this on the console:

I've been at this for days, wandering around stackoverflow and everywhere else, and I'm completely stuck... Can anyone please give me a hint on what can I do?

回答1:

axios.create({ baseURL: http://localhost:5000/ });

set baseURL before sending request.



回答2:

Ok so it seems I've found my own answer... Finally. Thank you all for your help!

The problem was pretty basic, pretty dumb. Simply the lack of "event.preventDefault()". Just that... Yeah call me stupid, I've been telling that to myself for the past hours