简体   繁体   中英

React JS - Fetch() Event Results in 404 Not Found

I've created a React JS app and added a fetch() event to a class but I'm unable to work out how to locate the file path as the resulting code leads to a 404 Not Found error in the console.

LoginForm.js:11 POST http://localhost:3000/api/user-login 404 (Not Found)

I am trying to locate user-login.js within /src/api/user-login.js

This is my folder structure:

https://monosnap.com/direct/DT5zykUaHOVz8YMJy9O96B762bOsvQ

Here is the relevant code within the class from LoginForm.js :

class LoginForm extends React.Component {
    handleSubmit(event) {
        var user = {
            'clientname': 'client name here',
            'email': 'client email here'
        };

        fetch('/api/user-login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(user)
        })
    }

    render() {
        // Stuff that gets rendered
    }
}

I have attempted every variation of /app/user-login that I can think of, including:

app/user-login
app/user-login.js
/app/user-login
/app/user-login.js
./app/user-login
./app/user-login.js
../app/user-login
../app/user-login.js

Could somebody please enlighten me on how I can link to this file? Sorry if this is a stupid question, I've only been learning React JS for a couple of days. Thanks for your help.

I hadn't set-up an API server which is why this was showing a 404 error. I had to use ExpressJS which means that any time my React app makes a request to something that's not a static asset (not an image or CSS or index.html, basically), it will forward the request to the server.

I used the following tutorial to do this:

https://daveceddia.com/create-react-app-express-backend/

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