Node.js React提供了错误的资产URL

4

我一直在经历节点问题,无法解决我的Create React App的路径。

问题:

Assets (chunk.js) 文件解析为相对路径而不是绝对路径。

当我从根目录 (example.com) 访问网站并命中 /games/ URL 时,一切正常。但是,如果我刷新页面,则会将 /games 添加到 URL 中。

例如:

http://movies-finder.surge.sh/movies/419704

^ 访问页面并刷新页面。

正确链接:

https://example.com/static/js/main.b9f8ee12.chunk.js

错误链接:(当用户刷新页面时发生)

https://example.com/games/static/js/main.e50e1c49.chunk.js

我只想确保我的资源被访问时不出现/games

(没有必要加上/games/),因此无法正常工作:(

文件夹结构:

-/
 - server.js
 - public
    - index.html
 - package.json
 - Build

Package.json:

{
  "name": "games-finder",
  "version": "0.1.2",
  "private": true,
  "homepage": ".",
  "proxy": "http://localhost:3001/",
  "dependencies": {
    // dependencies
  },
  "devDependencies": {
    // dev dependencies for the project.
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "server": "node-env-run server.js --exec nodemon | pino-colada",
    "dev": "run-p server start",
    "heroku-dev": "run-p server start"
  }
}

server.js:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3001;
const path = require('path');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(pino);

app.get('/api/greeting', (req, res) => {
  const name = req.query.name || 'World';
  res.send(JSON.stringify({ greeting: `Hello ${name}!` }));
});

if (process.env.NODE_ENV === 'production') {

  // Serve any static files
  app.use(express.static('build'));

  // Handle React routing, return all requests to React app
  app.get('*', (req, res) => {
   res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
  });
}

app.listen(port, () => console.log(`Listening on port ${port}`));

请帮我找出问题。我已经花了几天时间尝试调试这个问题。
我只是想确保我的资产被访问时不会遇到`/games`。

请分享一个 Github 仓库。没有 mcve,很难缩小问题范围。 - Matt Carlotta
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接