gpt4 book ai didi

node.js - GET 请求在 Node 和 Express App 中返回 html

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:17 24 4
gpt4 key购买 nike

我使用 Node 和 Express 创建了一个应用程序。当我发出 get 请求时,它会返回我从 Node 服务器渲染的 html 文件。我已经使用路由渲染了 html 文件。并且它继续为每个 get 请求发送 html 文件。

Node 应用程序代码

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;

如何克服这个问题?

最佳答案

只需将 Router(app); 放在渲染 index.html 逻辑之前:

Router(app);

app.get('/*',(req,res) => {
res.sendFile(path.join(__dirname,'./index.html'));
});

但是 Router.js 中的 XHR get 请求路径应该更具体,例如 /auth。您还可以检查 req.xhr 来区分请求是来自 XHR 还是只是渲染请求。

关于node.js - GET 请求在 Node 和 Express App 中返回 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41334892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com