【问题标题】:POST request returning index.html body instead of appropriate responsePOST 请求返回 index.html 正文而不是适当的响应
【发布时间】:2020-05-11 02:18:41
【问题描述】:

我一直在开发一个网络应用程序,当前端通过后端代理在本地托管时,所有发布请求都可以正常工作,后端代理托管在 heroku 上。但是,在部署前端(在 firebase 上)时,请求仍然成功返回,但不是 {success: true} 它从构建目录返回 index.html 文件,并对数据库执行任何操作。

heroku上的相关代码:

const app = express();
const port = process.env.PORT || 8080;

app.use(bodyParser.json());
app.use(cors());
app.use(express.static(path.join(__dirname, 'build')));
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Credentials", true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
  next();
});

app.post('/updateBoard', async (req, res) => {
  const { board_id, itemName, color, index, gameInfo } = req.body;
  await functions.updateBoard(board_id, itemName, color, index, gameInfo)
  res.send({ success: true })
})

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.listen(port, () => console.log(`App listening on port ${port}!`));

各自的前端函数:

const updateBoardData = async (
    board_id,
    itemName,
    color,
    index,
    gameInfo
  ) => {
    var res = await fetch("/updateBoard", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        board_id: board_id,
        itemName: itemName,
        color: color,
        index: index,
        gameInfo: gameInfo,
      }),
    });
    console.log(res);
  };

部署的输出: <!doctype html><html lang="en"><head> ... </html>

来自本地主机的输出: {“成功”:真}

【问题讨论】:

  • 嗨,你能添加你得到什么样的输出吗?如果能更清楚地理解它会很棒。
  • 嗨,两个请求都成功,状态为 200,但它从构建文件中输出整个 index.html。我已经更新了帖子以显示更多信息,如果我应该添加更具体的内容,请告诉我!

标签: node.js reactjs express heroku


【解决方案1】:

好的,我设法通过将 fetch 中的路由设置为 nameofproject.herokuapp.com/updateBoard 来解决此问题,因为显然代理在部署应用程序后不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多