首页 > 解决方案 > 节点js响应加载资源失败:服务器响应状态为404(未找到)

问题描述

我正在尝试在我的节点 js 与 apache2 Web 服务器后端与我的 React 前端之间建立初始连接。我是这一切的新手,并试图在部署之前使其在本地机器上工作。我阅读了有关 CORS 的信息并用它解决了访问源标头的问题,但我不明白我在这里缺少什么。

服务器运行并监听端口 3000 前端在端口 3001

我的前端代码是:

import React from 'react';
import axios from 'axios';

import logo from './logo.svg';
import './App.css';

export default class App extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
      axios.get(`/ping`, {
          headers: {
              "Access-Control-Allow-Origin": "*"
          }
      })
          .then(res => {

              const persons = res.data;
              this.setState({ persons });
          })
  }

  render() {
    return (
        <h1>dfdfdfdfdf{this.state.persons}</h1>
    )
  }
}

我的后端代码是:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var cors = require('cors');
var app = express();

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

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

const hostname = '127.0.0.1';
const port = 3000;

// 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.use(express.static(path.join(__dirname, 'build')))

app.get('/ping', (req, res) => {
  return res.send('pong')
})

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'))
})

app.listen(port, hostname, () => {
 console.log(`Server running at http://${hostname}:${port}/`);
});

module.exports = app;

我不断收到错误:

加载资源失败:服务器响应状态为 404(未找到)0.chunk.js:779 未处理的承诺拒绝:错误:请求失败,状态码为 404(匿名函数)(0.chunk.js:779)promiseReactionJob

标签: node.jsreactjswebserverapache2

解决方案


好的似乎它只在本地主机上工作,一旦我部署它它就不再工作并且我收到错误:

[Error] Could not connect to the server.
[Error] XMLHttpRequest cannot load http://127.0.0.1:3000/ping due to access control checks.
[Log] Error: Network Error (main.cfc7d370.chunk.js, line 1)
(anonymous function) — createError.js:16
(anonymous function) — xhr.js:83

[Error] Failed to load resource: Could not connect to the server. (ping, line 0)

我试图将 ip 从本地 ip 更改为我的服务器公共 ip,但后来我超时了

[Log] Error: timeout of 180000ms exceeded (main.9721eecc.chunk.js, line 1)
[Error] Failed to load resource: The request timed out. (ping, line 0)

这是我的虚拟主机文件

<VirtualHost *:80>
        # The ServerName directive sets the request scheme, hostname and port that
        # the server uses to identify itself. This is used when creating
        # redirection URLs. In the context of virtual hosts, the ServerName
        # specifies what hostname must appear in the request's Host: header to
        # match this virtual host. For the default virtual host (this file) this
        # value is not decisive as it is used as a last resort host regardless.
        # However, you must set it for any further virtual host explicitly.
        #ServerName www.example.com
        ServerName moneyapp
        ServerAlias 185.28.153.109
        ServerAdmin matan@localhost
        DocumentRoot /home/matan/frontend/build

        <Directory /home/matan/frontend/build>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        </Directory>

        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn

        ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

# For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

任何帮助将不胜感激谢谢!


推荐阅读