[英]Requests for JS and CSS giving index.html instead
我正在使用Express
和create-react-app
。
我的React應用程序是一種發展的方式,現在我正在嘗試通過Express服務器為其提供服務。
// server/app.js
const express = require('express');
const path = require('path');
const app = express();
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
// serve main file
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
module.exports = app;
(當我執行npm run build
時,將填充我的構建目錄。
我在Chrome中查看該頁面,並且在localhost:3000
加載該頁面時會發生什么,就是控制台打印出Uncaught SyntaxError: Unexpected Token <
,並且在Sources選項卡中它顯示我的CSS和JS文件的內容與index.html
:如該圖所示。
這似乎是一個可以識別的問題,所以希望有人以前見過。 我對從何處開始感到困惑,尤其是因為起初我實際上是從Express成功提供應用程序的。 然后開始發生這種情況,然后在隨機切換git分支並還原和重播更改后停止,然后再次開始發生。 所以我什至不知道是什么使它發生或不發生。
您的app.use(express.static...
調用似乎失敗了,因此所有請求(包括對靜態資產的請求)都由app.get('*', (req, res) => {
部分。
當您打算使用它來服務React應用程序時,我建議從樣板中汲取靈感,“看看它是如何完成的”。 我個人使用NYTimes的kyt項目,也有react-starter-kit。
請嘗試以下代碼更改,這些更改在express文檔中有詳細介紹-在express中提供靜態文件 :
更換
app.use(express.static(path.resolve(__dirname, '..', 'build')));
用
app.use(express.static('build'))
去掉
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
問題是"homepage": ...
在package.json
。
當npm run build
運行時,package.json中有一個主頁URL,該主頁URL具有非空路徑(例如像這樣的Github Pages URL, https ://username.github.io/project_name,其中“ / project_name”是路徑),它會更改期望/build
文件的位置。 對我的js和CSS的請求將轉到/project_name/static/...
而不是/static/...
它甚至在npm run build
的日志輸出中說:
The project was built assuming it is hosted at /project_name/.
You can control this with the homepage field in your package.json.
在我的本地主機上,它沒有托管在/project_name/
,因此路徑已關閉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.