【发布时间】: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的原因)