[英]Express.js serving generated index.html issue
我現在正在做一個虛擬項目來學習帶有 react 和 react 路由器的 express 和 webpack,我想將所有服務器請求重定向到 index.html,這樣在訪問不同的 URL 時就不會出現“無法獲取”錯誤。 現在我處於開發模式,問題是我正在使用 HtmlWebpackPlugin 提供生成的 HTML。 我嘗試了這段代碼,但在訪問除根 URL 之外的任何 URL 時,我得到的只是“ENOENT”錯誤。
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../build/index.html'), function(err) {
if (err) {
res.status(500).send(err);
}
});
});
這也是我的 webpack.config :
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './client/index.js',
output: {
path: path.join(__dirname, 'build'),
publicPath: '/',
filename: 'bundle.js',
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/,
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/,
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: 'client/index.html',
fileName: path.join(__dirname, 'build/index.html'),
}),
],
};
使用express可以解決這個問題嗎?
PS 也有人可以解釋為什么服務器在訪問根 URL 時會正常加載生成的 index.html。 我以為我正在使用上面的代碼片段攔截我的所有請求。 現在真的很迷茫
這是我的 server.js 文件:
const express = require('express');
const models = require('./models');
const expressGraphQL = require('express-graphql');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const schema = require('./schema/schema');
const path = require('path');
const app = express();
const MONGO_URI = 'some_uri';
mongoose.Promise = global.Promise;
mongoose.connect(MONGO_URI);
mongoose.connection
.once('open', () => console.log('Connected to MongoLab instance.'))
.on('error', error => console.log('Error connecting to MongoLab:',
error));
app.use(bodyParser.json());
app.use(
'/graphql',
expressGraphQL({
schema,
graphiql: true,
})
);
const webpackMiddleware = require('webpack-dev-middleware');
const webpack = require('webpack');
const webpackConfig = require('../webpack.config.js');
app.use(webpackMiddleware(webpack(webpackConfig)));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../build/index.html'),
function(err) {
if (err) {
res.status(500).send(err);
}
});
這是 package.json,我正在使用某些軟件包的舊版本,因為我正在遵循教程,但計划稍后更新它們:
{
"name": "graphql-learning-project-02",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon index.js --ignore client"
},
"author": "",
"license": "ISC",
"dependencies": {
"apollo-client": "^0.8.1",
"axios": "^0.15.3",
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-env": "^1.1.8",
"babel-preset-react": "^6.22.0",
"body-parser": "^1.16.0",
"connect-mongo": "^1.3.2",
"css-loader": "^0.26.1",
"express": "^4.14.0",
"express-graphql": "^0.6.1",
"express-session": "^1.15.0",
"graphql": "^0.8.2",
"html-webpack-plugin": "^2.26.0",
"lodash": "^4.17.4",
"mongoose": "^4.7.8",
"nodemon": "*",
"passport": "^0.3.2",
"passport-local": "^1.0.0",
"react": "15.4.2",
"react-apollo": "^0.9.0",
"react-dom": "15.4.2",
"react-router": "^3.0.2",
"react-router-dom": "^4.3.1",
"style-loader": "^0.13.1",
"webpack": "^2.2.0",
"webpack-dev-middleware": "^1.9.0"
}
}
webpack-dev-middleware沒有生成任何文件。
這意味着沒有生成index.html
。
根據其文檔:
沒有文件寫入磁盤,而是處理內存中的文件
請刪除:
app.get('*', (req, res) => { ...
在開發模式下服務器 webpack 文件:
app.use('*', webpackMiddleware(webpack(webpackConfig)))
app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../build/index.html') ...
可以在生產 webpack 構建后使用。
您可以使用connect-history-api-fallback中間件始終回退到 index.html。 這可以在開發和生產環境中使用。
像這樣使用它:
const connectHistoryApiFallback = require('connect-history-api-fallback');
...
app.use(connectHistoryApiFallback({
verbose: false
}));
// static files and folders must be set after connectHistoryApiFallback
app.use("/", express.static(__dirname));
app.listen(app.get('port'), (err) => {
console.info('Node app is running on port', app.get('port'));
});
如果有人仍然遇到此問題,那么您主要是像我一樣使用帶有webpack-dev-middleware和react-router 的express 。
我在使用軟件包的最新更新時找到了解決方案。
您可以在 webpack-dev-middleware 文檔中注意到writeToDisk選項默認設置為false 。 只需將其設置為true,同時仍然發送位於構建文件夾中的 index.html 文件。
對於那些還需要代理才能在 localhost:80 上使用 REST api 的人,這是我想出的服務器腳本:
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.config';
import proxy from 'express-http-proxy';
global.watch = true;
const compiler = webpack(webpackConfig);
const app = express();
const getPath = req => require('url').parse(req.url).path;
const createProxy = ({ hostname = 'localhost', path = '' }) => proxy(hostname, { proxyReqPathResolver: req => `${path}${getPath(req)}` });
export default async () => {
// Webpack dev Server
app.use(webpackDevMiddleware(compiler, {
writeToDisk: true,
noInfo: true,
stats: webpackConfig.stats,
publicPath: webpackConfig.output.publicPath
}))
// Hot module replacement
.use(webpackHotMiddleware(compiler))
// Proxy
.use('/api', createProxy({ path: '/api' }))
.use('/auth', createProxy({ path: '/auth' }))
// Static path
.use(express.static(webpackConfig.output.path))
// Handles routes
.get('/*', (req, res) =>{
res.sendFile(webpackConfig.output.path + '/index.html');
})
// Start
.listen(3000, (err) => {
if (err) {
console.error(err);
} else {
console.info('Listening to http://localhost:3000');
}
});
};
我正在使用 babel-node 來運行腳本,因此如果使用 node,請使用require而不是import 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.