GET请求在Node and Express App中返回html [英] GET request returns html in Node and Express App
问题描述
我已经使用Node with Express创建了一个应用程序.每当我发出get请求时,它都会从节点服务器返回即时消息渲染的html文件.我已经使用路由渲染了html文件,并且它会继续为每个get请求发送html文件.
I have created an app using Node with Express. when ever i make a get request it return the html file that im rendering from the node server. I have rendered the html file using a route.And it keep on sending the html file for every get request.
节点应用程序的代码
import express from 'express';
import mongoose from 'mongoose';
import bodyParser from 'body-parser';
import passport from 'passport';
import cros from 'cors';
import path from 'path';
import webpack from 'webpack';
import webpackmiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfig from '../webpack.config.dev';
import regusers from './models/regusers.model';
import Router from './routes/UserRouter';
const cross = cros();
const app = express();
const router = express.Router();
const port =3000;
const compile=webpack(webpackConfig);
const db='mongodb://localhost/parkspace';
mongoose.Promise = global.Promise;
mongoose.connect(db);
app.use(webpackmiddleware(compile,{
hot:true,
publicPath: webpackConfig.output.publicPath,
noInfo:true
}));
app.use(webpackHotMiddleware(compile));
app.use(cross);
app.use(router);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended:true
}));
app.get('/*',(req,res) => {
res.sendFile(path.join(__dirname,'./index.html'));
});
Router(app);
app.listen(port,()=> console.log('Running on port: '+port));
我的路由器文件
import Authentication from '../auth/auth';
import passportService from '../services/passport';
import passport from 'passport';
const requireAuth = passport.authenticate('jwt',{session:false});
const user = (app) => {
app.get('/',requireAuth,function (req,res){
res.send({hi:'there'});
});
app.post('/signup',Authentication.signup);
}
export default user;
如何克服这个问题?
推荐答案
只需在渲染 index.html
逻辑之前放置 Router(app);
:
Just put Router(app);
before your rendering index.html
logic:
Router(app);
app.get('/*',(req,res) => {
res.sendFile(path.join(__dirname,'./index.html'));
});
但是您在 Router.js
中获取XHR的路径应该更具体,例如/auth
.您还可以检查 req.xhr
来区分请求是来自XHR还是仅仅是呈现请求.
But your path for XHR get request in Router.js
should be more specific, like /auth
. You could also check req.xhr
to distinguish if a request is from XHR or just a rendering request.
这篇关于GET请求在Node and Express App中返回html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!