JS和CSS请求改为提供index.html [英] Requests for JS and CSS giving index.html instead

查看:94
本文介绍了JS和CSS请求改为提供index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Express create-react-app

我的React应用程序很不错,现在我正在尝试从Express服务器提供它。

My React app is a ways along, and now I'm trying to serve it from an Express server.

// 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文件的内容与<$ c完全相同$ c> index.html :如下图所示。

I view the page in Chrome, and what happens when loading the page at localhost:3000 is the Console prints Uncaught SyntaxError: Unexpected Token <, and in the Sources tab it shows that the content of my CSS and JS files are simply the same as index.html: as in this image.

这似乎是一个可识别的问题,所以希望有人以前已经看到过。我有点困惑从哪里开始,尤其是因为我实际上是从首先成功表达,然后开始发生,然后在随机切换git分支并还原和重放更改后停止,然后开始快乐宁。因此,我什至不知道是什么使它发生或不发生。

This seems like a recognizable issue, so hopefully someone has seen this before. I'm sort of stumped on where to even begin, especially because I was actually serving the app from Express successfully at first. Then this started happening, then it stopped after some random switching of git branches and reverting and replaying changes, and then it started happening again. So I'm not even sure what makes it happen or not happen.

推荐答案

看来您的 app.use(express.static ... 调用失败,因此,所有请求(包括对静态资产的请求)都由 app.get(' *',(req,res)=> {部分。

It appears that your app.use(express.static... call is failing, so instead all of the requests (including for the static assets) are being handled by the app.get('*', (req, res) => { part.

当您打算使用它来服务React应用时,我建议从样板中汲取灵感,看看它是如何完成的。我个人使用NYTimes的kyt项目,也有react-starter-kit。

As you are intending to use this to serve a React app, I'd suggest taking inspiration from a boilerplate, "to see how it's done". I personally use NYTimes's kyt project and there's react-starter-kit too.

这篇关于JS和CSS请求改为提供index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆