【问题标题】:React production API call outputting HTML page while dev API call outputs JSON反应生产 API 调用输出 HTML 页面,而开发 API 调用输出 JSON
【发布时间】:2018-10-01 05:18:52
【问题描述】:

我有一个 Mern 应用程序在开发环境中运行良好,但在生产环境中却不行。

在开发中,应用运行良好,但在生产中,api 调用失败并出现以下错误:

Uncaught (in promise) SyntaxError: Unexpected token

我使用邮递员进行测试,https://desolate-brushlands-16337.herokuapp.com/api/check 它正在输出构建文件夹的索引 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 }) )
}

【问题讨论】:

  • 能分享一下代码吗?
  • 好的 @AjayGupta 在我的 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()); //初始化路由 app.use('/api', require('/routes/api')); `
  • 请编辑您的原始帖子,而不是在评论中发布您的代码。
  • 我已经做到了@Striped
  • 你请求的响应不是JSON(Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0的原因)

标签: reactjs mern


【解决方案1】:

app.get('*'... 行中,您实际上是在告诉 express 为每个 get 请求提供 index.html,无论 URL 是什么。而是将此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'))
  })
};

【讨论】:

  • 请问我该如何实现?
猜你喜欢
  • 2023-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 1970-01-01
  • 2023-04-06
  • 2020-03-14
相关资源
最近更新 更多