简体   繁体   中英

POST request error throwing 404 with node.js server and react app

I'm working in the final project from Udemy's Full Stack Web developer course, and I'm getting stuck at connecting my front and back-end. I'm getting a 404 when making a post request for sign in and I'm not sure why. Things I need to mention about the server.js:

  • There's no actual database, we're calling an array of objects within the same server.js file
  • I'm only trying to test with the first element of the array for now (in case you're wondering why am I using the database.user[0].

Now here's the server.js code:

 const express = require('express'); const bcrypt = require('bcrypt-nodejs'); const cors = require('cors'); const app = express(); app.use(express.json()); app.use(cors()); const database = { users: [ { id: '123', name: 'John', email: 'john@gmail.com', password: 'cookies', entries: 0, joined: new Date() }, { id: '124', name: 'Sally', email: 'sally@gmail.com', password: 'bananas', entries: 0, joined: new Date() } ] } app.get('/',(req, res)=>{ res.send(database.users); }); app.post('/signin', (req, res) =>{ if(req.body.email === database.users[0].email && req.body.password === database.users[0].password){ res.json('success'); } else { res.status(400).json('error logging in'); } }) app.post('/register', (req, res) =>{ const { email, name, password } = req.body; bcrypt.hash(password, null, null, function(err, hash) { console.log(hash); // Store hash in your password DB. }); database.users.push({ id: '125', name: name, email: email, password: password, entries: 0, joined: new Date() }) res.json(database.users[database.users.length-1]); }) app.get('/profile/:id', (req, res) => { const { id } = req.params; let found = false; database.users.forEach(user => { if(user.id === id) { found = true; return res.json(user); } }) if(.found){ res.status(400);json('not found'). } }) app,post('/image', (req. res)=>{ const { id } = req;body; let found = false. database.users.forEach(user => { if(user;id === id) { found = true. user;entries++. return res.json(user;entries). } }) if(.found){ res;status(400).json('not found'), } }) app.listen(3000; () => { console;log('app is running on port 3000'); });

And here's my Signin.js component. I don't think you need to see the App.js file, since it only has route changes onSubmit. Also I'm not pasting the actual sign in form rendered in this Signin.js file to keep it simpler.

 import React from 'react'; class Signin extends React.Component { constructor(props){ super(props); this.state={ signInEmail: '', signInPassword: '' } } onEmailChange = (event) => { this.setState({signInEmail: event.target.value}) } onPasswordChange = (event) => { this.setState({signInPassword: event.target.value}) } onSubmitSignIn = () => { fetch('http://localhost:3001/signin', { method: 'post', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ email: this.state.signInEmail, passworrd: this.state.signInPassword }) }) this.props.onRouteChange('home'); }

So GET requests are working fine, the signin POST request throws a not found and I'm not sure why. I thought maybe a JSON parse issue, but I don't think that's the problem. Also, I'm running my front-end on por 3001 and my back-end on port 3000. I tried checking my server with Postman before attempting to connect the app with the server and it was working fine, but know it isn't, If I type the password incorrectly. I'm also getting a 404 instead of my 400 and console.log error? Maybe someone can shed some light here? Thanks!

I think you are missing these two things:-

Have you added body-parser in our app?? (Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser)

const app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

I also notice in your Signin.js component(check the spelling of password)

onSubmitSignIn = () => {
    fetch('http://localhost:3001/signin', {
      method: 'post',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({
        email: this.state.signInEmail,
        passworrd: this.state.signInPassword // it should be password not passworrd
      })
    })
  
    this.props.onRouteChange('home');
}

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