POST请求错误与node.js服务器一起抛出404并响应应用

时间:2020-09-23 06:51:09

标签: javascript node.js reactjs api express

我正在从事Udemy的Full Stack Web开发人员课程的最后一个项目,而我一直无法连接前端和后端。发出登录请求后,我收到404,但不知道为什么。关于server.js,我需要提及的事情:

  • 没有实际的数据库,我们在同一server.js文件中调用对象数组
  • 我现在仅尝试测试数组的第一个元素(以防万一您想知道为什么我要使用database.user [0]。

现在是server.js代码:

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');
});

这是我的Signin.js组件。我认为您不需要查看App.js文件,因为它仅在onSubmit上更改了路由。同样,我也不会粘贴此Signin.js文件中呈现的实际登录表单以使其更简单。

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');
   
  }

因此GET请求工作正常,登录POST请求抛出一个未找到的消息,我不确定为什么。我以为可能是JSON解析问题,但我不认为这是问题。另外,我在por 3001上运行我的前端,并在端口3000上运行我的后端。在尝试将应用程序与服务器连接之前,我尝试使用Postman检查服务器,并且运行正常,但知道它不起作用!如果我输入的密码不正确,我还会得到一个404错误而不是我的400和console.log错误。也许有人可以在这里说些什么?谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您缺少这两件事:-

您是否已在我们的应用程序中添加了body解析器? (包含在请求正文中提交的键-值数据对。默认情况下,它是未定义的,并且在使用诸如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

我还注意到您的Signin.js组件(检查密码的拼写)

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');
}