简体   繁体   English

使用express.js路由设置来响应应用

[英]react app with express.js route setup

I was using angular.js and I do this in express.js 我使用的是angular.js,我在express.js中执行此操作

app.get("*", function (req, res) {
  res.redirect('/#' + req.originalUrl)
})

so that the browser will use the route of angular instead of express. 这样浏览器将使用角度路线而不是快速路线。 But how to do that with react router? 但是如何用React Router做到这一点呢? I have 2 folder, named server and client, server folder has express and api logic while client folder simply a react app. 我有2个文件夹,分别命名为服务器和客户端,服务器文件夹具有express和api逻辑,而客户端文件夹只是一个react应用。

You need to put the path in of the HTML file you are rendering your app to 您需要将要呈现应用程序的HTML文件的路径放入

app.get("/",(res,res) => {
res.sendFile('put the path of the html file you are rendering your app into here');
}

here is an example of a express server.js that works with react 这是一个与react一起工作的express server.js的示例

var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');

var app = express();
var PORT = process.env.PORT || 3000;

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.text());
app.use(bodyParser.json({type: 'application/vnd.api+json'}));

app.use(express.static('./public'));

app.get('/', function(req,res){
    res.sendFile('./public/index.html');
});


app.listen(PORT, function(){
    console.log("Listening on port: " +  PORT);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM