【问题标题】:GET request returns html in Node and Express AppGET 请求在 Node 和 Express App 中返回 html
【发布时间】:2016-12-26 18:20:11
【问题描述】:

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

节点应用代码

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;

如何克服这个问题?

【问题讨论】:

    标签: node.js reactjs express


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      我认为这是因为在你的路由中有一个通配符/*,所以无论你去哪里,都会发送 html 文件。

      希望这会有所帮助。

      【讨论】:

      • 是的,我知道,但是如何避免在发出获取请求时获取 html 文件?我需要像这样为 html 文件提供服务,因为我使用的是单页应用程序 react 并定义单独的路由来提供 html 文件将无济于事。
      • 我没有使用 React 的经验,但我想这不是完成你想要的事情的方法。在 SPA 中,您不会每次都呈现/发送索引文件,而只是其内容。也许你应该把它作为一个 React 主题发布。你会得到更好的帮助!
      猜你喜欢
      • 2022-11-07
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 2021-04-23
      相关资源
      最近更新 更多