【问题标题】:POST request error throwing 404 with node.js server and react app使用 node.js 服务器和反应应用程序引发 404 的 POST 请求错误
【发布时间】:2020-09-23 06:51:09
【问题描述】:

我正在完成 Udemy 的全栈 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 文件,因为它仅在提交时更改了路由。此外,我没有粘贴此 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 解析问题,但我认为这不是问题所在。另外,我在端口 3001 上运行我的前端,在端口 3000 上运行我的后端。在尝试将应用程序与服务器连接之前,我尝试使用 Postman 检查我的服务器,它工作正常,但知道它不是!如果我输入的密码不正确,我也会收到 404 而不是我的 400 和 console.log 错误。也许有人可以在这里阐明一下?谢谢!

【问题讨论】:

  • 你检查过端口吗?
  • 根据您的代码,您的/signin 位于端口 3000 - 您的代码请求端口 3001
  • 您是否检查过您的 fetch 请求中是否发布了任何数据?通过控制台两端请求的数据。
  • @xMayank 是的,不是那样的。
  • @SachinKumar 谢谢,它现在可以工作了,刚刚添加了一个 event.preventDefault();在 onSubmitSignIn 函数中

标签: javascript node.js reactjs api express


【解决方案1】:

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

您是否在我们的应用程序中添加了正文解析器? (包含请求体中提交的数据键值对,默认未定义,使用body-parser等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');
}

【讨论】:

  • 我没有使用正文解析器,因为 express 现在具有该功能。确实密码拼错了,但事实并非如此!我添加了一个 event.preventDefault();而且我在 stringify 函数中显然遗漏了一个逗号!它现在正在工作。非常感谢!
猜你喜欢
  • 1970-01-01
  • 2016-04-02
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多