【问题标题】:Web page returns status code of 404, but renders properly网页返回 404 状态码,但正确呈现
【发布时间】:2021-04-09 04:23:15
【问题描述】:

我正在使用 React 和 create-react-app 创建一个网站。该站点完全按预期工作,但是,当我在站点上运行测试时,测试结果与预期结果不符。在测试来自我的网站的响应时(即,如果页面存在并正确加载等),所有页面都返回状态代码 404,但“/”除外,它应该返回状态代码 200。使用网站上的链接在组件之间导航可以正确加载它们,输入页面的确切 URL 也是如此(即“localhost:5000/example”),但是在开玩笑地测试页面时,它们都返回 404。

我知道,由于我的网站是 SPA,React 可能无法正确自动处理指向特定组件的直接链接,但让我感到困惑的是,任何页面上都没有错误、警告或缺少功能,但在运行时页面上的测试所有页面都返回 404,除了“/”,它应该对应于 index.html,因此即使 React 不能正常工作,请求也不应该失败。我找不到其他人遇到这个问题,因为其他人从 React 得到错误的 404 也无法输入组件的特定地址并使其工作。

我的问题是如何防止页面/组件在它们明显正常工作时返回 404 状态代码,或者如果这不是问题,我如何让我的单元测试识别页面按预期工作?

这是我的 App.js

function App() {
  return (
    <Provider store={store}>
      <Router>
        <div className="container">
          <Navbar />
          <br />
          <Route path="/" exact component={HomePage} />
          <Route exact path="/example" component={ExamplePage} />
        </div>
      </Router>
    </Provider>
  );
}

export default App;

主页.js

import React, { Component } from 'react';

export default class HomePage extends Component {
    render() {
        return (
            <div>
                <h4>Home page</h4>
            </div>
        )
    }
}

ExamplePage.js

import React, { Component } from 'react';

export default class ExamplePage extends Component {
    render() {
        return (
            <div>
                <h4>A bunch of text here.</h4>
            </div>
        )
    }
}

App.test.js

describe('Client Unit Tests', function () {
  //Unit test 1: check server response
  describe('Client responds to requests', function () {
    it('should respond', function (done) {
      request.get(site_url, function (error, response, body) {
        should.exist(response, 'Response is either null or undefined');
        done();
      });
    });
  });

  // Unit test: check pages
  describe('Client responds properly to all valid page requests', function () {
    // Unit test 2: Check home page
    it('responds correctly to a GET request to ""', function (done) {
      request.get(site_url, function (error, response, body) {
        should.exist(response, 'Body is either null or undefined');
        should.notStrictEqual(response.statusCode, 404, '404 Page not found');
        done();
      });
    });

    // Unit test 3: Check example page
    it('responds correctly to a GET request to "/example"', function (done) {
      console.log(site_url + '/example');
      request.get(site_url + '/example', function (error, response, body) {
        should.exist(response, 'Body is either null or undefined');
        should.notStrictEqual(response.statusCode, 404, '404 Page not found');
        done();
      });
    });
  });
});

编辑: 忘记了我的 server.js 代码

const app = express();
const hostname = process.env.HOST || "localhost";
const port = process.env.PORT || 5000;

// Serve client
app.use('/', express.static(path.join(__dirname, '../client/build')));

// Load dependencies
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());

// Connect to MongoDB
const uri = require("./config/keys").mongoURI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
    .then(() => console.log("MongoDB database connection established successfully"))
    .catch(err => console.log(err));

// Serve static routes
app.get("*", (req, res) => {
    res.sendFile(path.join(__dirname, "../client", "build", "index.html"));
});

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

【问题讨论】:

  • 我假设您的反应应用程序前面有一个网络服务器?阿帕奇,nginx? iis?快递应用?当请求 / 以外的任何页面时,是什么告诉网络服务器服务 / ?鉴于您所看到的,我假设它是 404 处理程序。
  • 哦,对了,我忘了包括我的服务器代码。我正在使用 express,我在编辑中包含了代码。
  • 我不认为代码对您看到的 404 负责。
  • 除了 api 路由,我真的没有任何其他的服务器代码,但这些对页面或其状态代码没有影响。

标签: javascript reactjs jestjs create-react-app


【解决方案1】:

React 无法发送状态码。只有在页面加载后才会激活 React。状态代码来自您的服务器。 Express 没有内置的包罗万象的路线。因此,您的 app.use('/') 使其适用于 / 路由,但所有其他路由都不起作用。转到http://localhost:5000/* 也应该可以。要解决此问题,您需要执行以下操作:

app.use((_err, req, res, next) => {
    if (req.method === "GET") {
        res.sendFile(path.join(__dirname, "../client", "build", "index.html"));
    } else {
        next();
    }
});

【讨论】:

    猜你喜欢
    • 2020-10-10
    • 2018-04-05
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多