我试图在/物种上使用json,但是,无论我使用什么路线,表达似乎总是加载反应应用程序。任何人都可以弄清楚什么是错的?这是我的server.js文件:
const app = require('express')();
const cors = require('cors')
const bodyParser = require('body-parser');
const path = require('path');
const express = require('express');
//Enable CORS app.use(cors());
const species = [ {
name: 'mallard' } ];
const sightings = [ {
id: '1',
species: 'gadwall',
description: 'All your ducks are belong to us',
dateTime: '2016-10-01T01:01:00Z',
count: 1 }, {
id: '2',
species: 'lesser scaup',
description: 'This is awesome',
dateTime: '2016-12-13T12:05:00Z',
count: 5 } ];
//Enable CORS app.use((req, res, next) => { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); });
app.use(bodyParser.json());
app.get('/sightings', (req, res) => {
res.json(sightings); });
app.post('/sightings', (req, res) => {
req.body.id = (sightings.length + 1).toString();
sightings.push(req.body);
res.json(req.body); });
app.get('/species', (req, res) => { res.json(species); });
app.use(express.static(path.resolve(__dirname, './react-front/build')));
app.get("*", (req, res) => { response.sendFile(path.resolve(__dirname, './react-front/build', 'index.html')); });
const port = process.env.PORT ? process.env.PORT : 8081; const server
= app.listen(port, () => {
console.log("Server listening port %s", port); });
答案 0 :(得分:0)
我认为您可以通过将要使用React的路由分开来解决此问题。
例如,您可以为要与React一起使用的应用程序编写一个新的Express模块并将其导出:
const express = require('express');
const router = express.Router();
// Use 'react-front/build' for router, but not
// your main Express application.
router.use(express.static(path.resolve(__dirname, './react-front/build')));
router.get('/something', function(req, res) {
// Do something here
});
module.exports = router;
然后在您的快递应用中添加以下内容
// Require the module
const reactRouter = require('./path/to/router');
app.use(reactRouter);