简体   繁体   中英

Axios POST request in react to Express server is returning 404

I am using Axios in my react-app. Running the react app on server port 3000 and express server on port 31001

My react component--

import React from 'react';
import {Form,Button} from 'react-bootstrap';
import { Link,useHistory } from 'react-router-dom';
import Axios from "axios";

export default function Register(){
    let history = useHistory();
    
    function signMeUp(e){
        e.preventDefault()
        let userName = document.getElementById('username')?.value
        let password = document.getElementById('password')?.value
        let data = {
            userName:document.getElementById('username')?.value,
            password:document.getElementById('password')?.value,
        }
        
        Axios({
            method: "POST",
            url: "http://localhost:31001/register",
            data,
            headers: {
              "Content-Type": "application/json"
            }
          }).then(res => {
            console.log(res.data.message);
          });


        console.log(userName, password)
        
        if(userName && password){
            history.push("/Login");
        }
        else{
            alert('Enter a username / password')
        }
    }

    return(
        <div style={{width:"50vw",margin:"auto",marginTop:"50px"}}>
              <h1 style={{textAlign:"center",paddingBottom:"30px"}}>Book My Movie</h1>
              <h1 style={{textAlign:"center"}}>Register</h1>
              <Form onSubmit={(e)=>{signMeUp(e)}}>
                <Form.Group controlId="formBasicEmail">
                    <Form.Label>Email address</Form.Label>
                    <Form.Control type="email" placeholder="Enter email" id="username"  />
                    <Form.Text className="text-muted">
                    </Form.Text>
                </Form.Group>
              
                <Form.Group controlId="formBasicPassword">
                    <Form.Label>Password</Form.Label>
                    <Form.Control type="password" placeholder="Password" id="password" />
                </Form.Group>
                <Button variant="primary" type="submit" style={{width:"100%"}}>
                    Submit
                </Button>
                <div  style={{textAlign:"center",margin:"auto"}}>
                   <Link to="/Login">Already have a account ? Login Here</Link>
                </div>
              </Form>
        </div>
    );
}

My server.js

const express = require("express"),
    app = express(),
    port = process.env.PORT || 31001,
    cors = require("cors");

app.use(cors());
app.listen(port, () => console.log("Backend server live on " + port));

app.get("/register", (req, res) => {
    res.send({ message: "We did it!" });
});

I have also placed a proxy on package.json::

  "proxy": "http://localhost:31001",

This is the error i am receiving on chrome console:

xhr.js:184 POST http://localhost:31001/register 404 (Not Found)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 404
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:69)

I have read almost all stackoverflow solutions but didnt worked for me.

The method should be post in express app.post("/register", (req, res) => {.. because i front-end you're doing method: "POST", :

 Axios({
            method: "POST",
            url: "http://localhost:31001/register",
            data,
            headers: {
              "Content-Type": "application/json"
            }
          }).then(res => {
            console.log(res.data.message);
          });

You are requesting POST but you are listening a GET request. You have to change the express route to a post request listener.
In this case you will be able to get the request body instead (in case you are sending) :

app.post("/register", (req, res) => { //<---change to post
   res.json({ message: "We did it!" }); // <----res.json to send data as json.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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