Javascript Express.js服务生成的index.html问题
我现在正在进行一个虚拟项目,学习使用react和react router的express和webpack,我想将所有服务器请求重定向到index.html,这样在访问不同URL时就不会出现“无法获取”错误。现在我处于开发模式,问题是我正在使用HtmlWebpackPlugin提供生成的HTML。我尝试了这段代码,但在访问除根URL之外的任何URL时,我得到的都是“enoint”错误Javascript Express.js服务生成的index.html问题,javascript,reactjs,express,webpack,react-router,Javascript,Reactjs,Express,Webpack,React Router,我现在正在进行一个虚拟项目,学习使用react和react router的express和webpack,我想将所有服务器请求重定向到index.html,这样在访问不同URL时就不会出现“无法获取”错误。现在我处于开发模式,问题是我正在使用HtmlWebpackPlugin提供生成的HTML。我尝试了这段代码,但在访问除根URL之外的任何URL时,我得到的都是“enoint”错误 app.get('*', (req, res) => { res.sendFile(path.join(__
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解决此问题
另外,还有人可以解释为什么服务器在访问根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"
}
}
未生成任何文件。这意味着没有生成
index.html
根据:
没有文件写入磁盘,而是它处理内存中的文件
请删除:
app.get('*', (req, res) => { ...
要在开发模式下服务器Web包文件,请执行以下操作:
app.use('*', webpackMiddleware(webpack(webpackConfig)))
app.get('*',(req,res)=>{res.sendFile(path.join(uu dirname,../build/index.html')…
可在生成生产网页包后使用。您可以使用中间件始终回退到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'));
});
如果有人仍然遇到此问题,您主要使用express和webpack dev middleware以及react router,就像我一样 我在使用软件包的最新更新时找到了一个解决方案 您可以在webpack dev middleware文档中注意到,默认情况下选项设置为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。您可以发布整个express主文件吗?如果没有看到它,很难判断是否有其他冲突导致此行为。谢谢!@MikeAbeln嘿,我今天晚些时候会发布它,但现在我还没有详细信息访问代码时,我记得使用了webpack中间件,可能是它导致了服务器的某些行为。是的,这是可能的,但我们需要查看您的服务器js配置。此外,您是否可以发布您的package.json,以便我们可以查看您有哪些可用的软件包以及哪些版本?@c-chavez嘿,我更新了描述with server.js和package.json.oh我明白了,这解释了它在访问根url时如何为index.html服务,但在访问任何其他url时,我仍然无法重定向到内存中的index.html(例如,我获取“无法获取/列表”)。此外,当我使用
app.use('*',webpackMiddleware(webpack(webpackConfig)))
,我在控制台中遇到语法错误,说Uncaught SyntaxError:Unexpected token<(bundle.js 1)。它只在我将“*”替换为“/”时起作用,但没有从其他url重定向,这是我的主要目标:(.解释是有道理的,但我尝试过,我得到的都是错误,因为当访问/dashboard/results这样的路由时,页面无法加载js块。我试图找到一种方法,将react router与express和webpack dev中间件结合使用,同时避免访问index.html内置的产品,顺便说一句,它不是最新的。