当dev API调用输出JSON时,React生产API调用输出HTML页面

问题描述 投票:0回答:1

我有一个Mern应用程序在dev上工作正常但不在生产上。

在开发应用程序上工作正常,但在生产时api调用失败并出现此错误:

未捕获(在promise中)SyntaxError:在位置0的JSON中出现意外的令牌

我使用postman测试,https://desolate-brushlands-16337.herokuapp.com/api/check,它输出build文件夹的索引html页面。我还测试了http://localhost:3000/api/check并输出了JSON。

这是我的server.js文件中的代码

   const app = express();

const dev = app.get('env') !== 'production';

if(!dev){

  app.disable('x-powered-by');
  app.use(express.static(path.resolve(__dirname, 'client/build')));
  app.get('*',(req, res)=>{

    res.sendFile(path.resolve(__dirname, 'client/build', 'index.html'))

  })
};

app.use('/uploads', express.static(__dirname + '/uploads'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json()); 





//initialize routes
app.use('/api', require('/routes/api')); 

and the code in my fetch code on the react section

 componentDidMount = () =>{

fetch(window.location.protocol + '//' + window.location.host + `/api/check`)
        .then(res => res.json())
        .then (post_contents => this.setState({ post_contents }) )
}
reactjs mern
1个回答
1
投票

app.get('*'...行中,无论URL是什么,你实际上都在告诉express为每个get请求提供index.html。而是将此if条件移动到文件的末尾,或者更确切地说,在声明其他路径之后。这将确保Express首先检查路由是否未指定任何其他响应。

履行

以下是代码中必要的更改

const app = express();
const dev = app.get('env') !== 'production';

app.use('/uploads', express.static(__dirname + '/uploads'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', require('/routes/api')); // Declare other routes before the wildcard.

if(!dev){
  app.disable('x-powered-by');
  app.use(express.static(path.resolve(__dirname, 'client/build')));
  app.get('*',(req, res)=>{
    res.sendFile(path.resolve(__dirname, 'client/build', 'index.html'))
  })
};
© www.soinside.com 2019 - 2024. All rights reserved.