Express.js 将HTML文件当成JS来渲染了
发布于 7 年前 作者 vividwang 3084 次浏览 来自 问答

打包好前端文件之后,后端使用express,用浏览器访问发现返回了三个个文件,一个localhost,一个js文件,一个css文件,js文件中的内容是原本index.html的内容屏幕快照 2018-03-20 08.47.41.png,然后浏览器报错:Uncaught SyntaxError: Unexpected token <

curl -i http://localhost:8000 HTTP/1.1 200 OK X-Powered-By: Express Accept-Ranges: bytes Cache-Control: public, max-age=0 Last-Modified: Mon, 19 Mar 2018 13:14:03 GMT ETag: W/"224-1623e653934" Content-Type: text/html; charset=UTF-8 Content-Length: 548 Date: Tue, 20 Mar 2018 01:19:07 GMT Connection: keep-alive

<!DOCTYPE html><html lang=“en”><head><meta charset=“utf-8”><meta name=“viewport” content=“width=device-width,initial-scale=1,shrink-to-fit=no”><meta name=“theme-color” content="#000000"><link rel=“manifest” href="/manifest.json"><link rel=“shortcut icon” href="/favicon.ico"><title>React App</title><link href="/static/css/main.493795e3.css" rel=“stylesheet”></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id=“root”></div><script type=“text/javascript” src="/static/js/main.2b8842f0.js"></script></body></html>

6 回复

后端代码如下 /**

  • Created by w on 2018/3/16. */ const express = require(‘express’); const app = express(); const router = require(’./router’); const path = require(‘path’); const bodyParser = require(‘body-parser’);

app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false}));

app.use(’/user’, router);

app.use(’/’,(req,res,next)=>{ console.log(path.resolve(‘build/index.html’)); res.sendFile(path.resolve(‘build/index.html’)); });

app.use(express.static(path.resolve(‘build’)));

let server = app.listen(8000, function () { let host = server.address().address; let port = server.address().port;

console.log('Server running at http://%s:%s', host, port);

});

app.use('/', express.static(path.resolve(‘build’)));

@MiYogurt 这样也是不行的

注释掉这一句试试

//app.use(’/’,(req,res,next)=>{ //console.log(path.resolve(‘build/index.html’)); //res.sendFile(path.resolve(‘build/index.html’)); //});

@dbit-xia 这样会出现错误: Uncaught SyntaxError: Unexpected end of input main.617d6863.js:1

app.use('/static', express.static(__dirname + '/build'));
app.use('*', (req,res) => {res.sendFile('./build/index.html')})

index.html 的 js 记得要加上 static

仔细阅读下文档不就知道了么。

回到顶部