You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Heroku报Cannot Get /:本地正常的API部署后无法访问

Heroku API部署问题排查

现状概述

首次尝试在Heroku部署API,试过多种方案后问题反而增多。

已确认信息

  • Heroku动态生成端口功能正常
  • MongoDB引用问题已修复(曾触发URI() must be a string错误)
  • heroku local web本地运行正常,执行heroku restart无效果

遇到的困惑与未解决问题

看到有人推荐以下代码,但不清楚build文件夹的用法,且这段代码未解决我的问题:

const path = require('path');
if (process.env.NODE_ENV === 'production') {
  //set static folder
  server.use(express.static('client/build'));
}
server.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});

当前核心问题:

  • 日志中出现SyntaxError: Unexpected end of input错误
  • 应用构建成功,状态显示为“up”,但访问页面时发送的Get请求无响应

我的API代码

const express = require('express');
const mongoose = require('mongoose');
const toDoRoutes = require('./routes');

//creates server and sets use cases to handle JSON and todo routes
const server = express();
server.use(express.json());

//sets headers to allow apps to interact with eachother
server.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept, Authorization'
  );
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');

  next();
});

server.use('/api/todos', toDoRoutes);

//connects mongodb server to API and then starts server on success
mongoose
  .connect(`${process.env.DB}`)
  .then(() => {
    server.listen(process.env.PORT || 3001);
  })
  .catch((error) => console.log(error.message, db));

内容的提问来源于stack exchange,提问作者HarrySIV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:54:36