找不到404 React JS和Express POST路由

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了找不到404 React JS和Express POST路由相关的知识,希望对你有一定的参考价值。

我的问题是我正在尝试向我的项目添加编辑功能。我已将/edit路由器添加到我的classroom.js文件中,然后我通过应用程序编辑标志,并在控制台日志中获取POST /classroom/edit 404 398.484 ms - 1355。在浏览器控制台日志中,我得到:

App.js:32 POST http://localhost:3002/classroom/edit 404 (Not Found)
App.js:52 Error: Bad response from server
    at App.js:40

反应:App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      toggle: false,
      toggleIdx: 0,
      classroom: [],
      flagreason: '',
      msg: ''
    };
    this.eventHandler = this.eventHandler.bind(this);
    this.logChange = this.logChange.bind(this);
    this.handleEdit = this.handleEdit.bind(this);
  }

  logChange(e) {
    this.setState({
      [e.target.name]: e.target.value
    });
  }

  handleEdit(event) {
    event.preventDefault()
    var data = {
      flagreason: this.state.flagreason,
      id: this.state.toggleIdx
    }
    fetch("/classroom/edit", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    }).then(function(response) {
      if (response.status >= 400) {
        throw new Error("Bad response from server");
      }
      return response.json();
    }).then(function(data) {
      console.log(data)
      if (data === "success") {
        this.setState({
          msg: "Flag Reason has been edited."
        });
        console.log('Successful Update!');
      }
    }).catch(function(err) {
      console.log(err)
    });
  }

  eventHandler(event, idx) {
    this.setState((prevState) => ({
        toggle: !prevState.toggle,
        toggleIdx: idx
      })
    );
  }

  componentDidMount() {
    fetch("/classroom")
    .then(res => res.json())
    .then(classroom => this.setState({ classroom }))
  }

  render() {
    return (
      <div className="App">
                <div className="wrapper">
                    <h1>Classroom</h1>
                    {this.state.classroom.map((classroom, idx) =>
                        <div className="child" key={classroom.id}>
              <p className="detail">Child's Name: <span className={classroom.childflagged}>{classroom.childsname}</span> <i title={classroom.flagreason} className={'fa fa-flag flag' + classroom.childflagged}></i><i title={classroom.starreason} className={'fa fa-star star' + classroom.starstudent}></i></p>
              <p className="detail">Parent's Phone Number: {classroom.parentsnumber}</p>
              <div className="actionMenu">
                <button className="flags" id={classroom.id} onClick={e => this.eventHandler(e, idx)}>Edit Flags</button>
                <button className="results">View Results</button>
                <button className="profile">View Profile</button>
              </div>
              <div className="actionForm">
                <div>
                  <form id={"flagform" + classroom.id} className={(this.state.toggle && (this.state.toggleIdx === idx)) ? '' : 'hide'} onSubmit={this.handleEdit} method="post" autoComplete="no">
                    <input type="hidden" name="id" value={classroom.id} />
                    <input type="text" onChange={this.logChange} value={this.state.flagreason} name="flagreason" placeholder="Reason For Flag" />
                    <input type="submit" name="submit" value="Save Changes" />
                  </form>
                </div>
              </div>
            </div>
          )}
                </div>
      </div>
    );
  }
}

export default App;

快递:app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var index = require('./routes/index');
var classroom = require('./routes/classroom');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/classroom', classroom);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.listen(3001);

module.exports = app;

classroom.js

var express = require('express');
var router = express.Router();
var mysql = require('mysql');

var pool = mysql.createPool({
  connectionLimit : 30,
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'dbname'
});

/* GET Classroom listing. */
router.get('/', function(req, res, next) {

    console.log('A Client Requested Data...');

  pool.query('SELECT * FROM classroom ORDER BY childsname ASC', function(err, results) {
    if (err) throw err
    var array = [];
    for(var i = 0, len = results.length; i < len; i++) {
      array.push(results[i]);
    }

        res.json(array);
    });

});

/* EDIT Child Flag */

router.get('/edit', function(req, res, next) {

  console.log('A flag was edited...');

  pool.query("UPDATE classroom SET flagreason = '"+req.body.flagreason+"' WHERE id = '"+req.body.id+"'", function (err, results, fields) {
      if(err) throw err;
      res.send(JSON.stringify(results));
  });
});

module.exports = router;

谁能帮助我,展示我需要改变的东西,然后解释为什么它不起作用所以我可以从错误中吸取教训?

答案

您需要更新服务器上classroom.js文件的一部分才能使用post方法:

router.post('/edit', function(req, res, next) {

  console.log('A flag was edited...');

  pool.query("UPDATE classroom SET flagreason = '"+req.body.flagreason+"' WHERE id = '"+req.body.id+"'", function (err, results, fields) {
      if(err) throw err;
      res.send(JSON.stringify(results));
  });
});

目前它正在期待GET请求并且您正在发送POST,因此它不知道如何处理它。其余的应该没问题。

另一答案

基于提供的代码,似乎有2个问题导致404.第一个是在你的反应代码中你正在做一个post请求,但它的路线是get

第二个问题是,在您的反应代码中,您试图到达/classroom/edit,但根据提供的代码,它应该只是/edit

UPDATE

随着提供的附加代码,问题似乎是因为你试图使postget路线。

反应代码中的路由实际上应该是/classroom/edit,路由处理程序应该更改为post

以上是关于找不到404 React JS和Express POST路由的主要内容,如果未能解决你的问题,请参考以下文章

使用 Django + react-router 找不到 404 页面

Django React -- Heroku 上的部署错误(找不到页面 404)

找不到 bundle.js

React app Express Api无法运行localhost 404(未找到)

当页面刷新“404 - 找不到文件或目录”时。

在提交 Vue js 和 Laravel 时找不到 POST 404?