【问题标题】:ReactJS - Failed to load resource: the server responded with a status of 404 (Not Found)ReactJS - 加载资源失败:服务器响应状态为 404(未找到)
【发布时间】:2019-03-03 00:00:38
【问题描述】:

我对 ReactJS 完全陌生。

我在 YouTube 上关注这个tutorial,并按照每个步骤进行操作。

直到我发现我的代码出现类似this的错误

由于我是 ReactJS 编程新手,我仍然不明白该怎么做,以及如何解决这个问题

本教程展示了如何在 ReactJS 和 PostgreSQL 中构建一个简单的 CRUD 应用

在这里我提供我的 App.js 代码

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

class App extends Component {
  constructor(){
   super(); 
   this.state={
   title: 'Simple Guestbook',
  guestbooks: []
}
}
componentDidMount(){
console.log('Component has mounted')
}
addGuest(event){
event.preventDefault();

let data = {
  guestname: this.refs.guestname.value,
  guestaddress: this.refs.guestaddress.value
};
var request = new Request("http://localhost:3000/api/new-guest", {
  method: 'POST',
  headers: new Headers({'Content-Type': 'application/json'}),
  body: JSON.stringify(data)
});

//xmlhttprequests
fetch(request)
  .then(function(response){
    response.json()
      .then(function(data){
        console.log(data)
      })
  })
  }
render() {
let title = this.state.title;
return (
  <div className="App">
<h1>Assalaamu'alaykum</h1>
    <h2>{title}</h2>
    <form ref="guestbookForm">
      <input type="text" ref="guestname" placeholder="guest name"/>
      <input type="text" ref="guestaddress" placeholder="guest address"/>
      <button onClick={this.addGuest.bind(this)}>Add Guest</button>
    </form>
  </div>
);
}
}
export default App;

这是我的 server.js 代码:

 let express = require('express');
    let bodyParser = require('body-parser');
    let morgan = require('morgan');
    let pg = require('pg');

    const PORT = 3000;

    let pool = new pg.Pool({
    port:5432,
    password: 'qwerty',
    database: 'guestbook',
    max: 10,
    host: 'localhost',
    user: 'postgres'
    });

    let app = express();

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));

    app.use(morgan('dev'));
    app.use(function(request, response, next) {
       response.header("Access-Control-Allow-Origin", "*");
       response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
      });
      app.post('/api/new-guest', function(request, response){
    console.log(request.body);
      });
      app.listen(PORT, () => console.log('Listening to Port '+ PORT));

我该怎么办?任何建议都会帮助我解决这个问题

谢谢...

【问题讨论】:

  • 这几乎没有任何重要的细节可以回答这个问题。它也快 3 岁了,所以...

标签: javascript reactjs express


【解决方案1】:

使用箭头功能,

fetch(request)
  .then((response) => {
    return response.json()
  }).then((data) => {
        console.log(data)
 })

【讨论】:

  • 嗨,Anshuman,我已经尝试了您对我的建议。但它仍然抛出。 “加载资源失败:服务器响应状态为 404(未找到)”我是否应该创建一些内容以便服务器可以找到未找到的内容?
  • 我没有改变任何东西,知道吗?我错过了什么吗?谢谢
猜你喜欢
  • 2015-12-01
  • 2018-08-09
  • 1970-01-01
相关资源
最近更新 更多