0
我試圖在/物種中使用JSON,但是,無論我使用什麼路線,express都似乎總是加載反應應用程序。任何人都可以弄清楚什麼是錯的?這是我的server.js文件:無論我使用哪條路線,Express都加載了我的React應用程序,出了什麼問題?
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); });
歡迎來到Stack Overflow!有關您嘗試完成什麼/爲什麼以及目前嘗試完成的更多信息將對您有所幫助。有關於發佈問題的[一些提示](https://stackoverflow.com/help/how-to-ask)。 – ashleedawg
看起來您正在重複發送此行上的靜態資產:app.get('*',...)。嘗試沒有它。 – Splitty
@Splitty實際上並沒有改變任何東西。它仍然在任何路線上呈現反應應用程序。我試圖將信息從本地主機上的jsons呈現給反應應用程序。 – ejexet