简体   繁体   English

POST 请求返回 index.html 正文而不是适当的响应

[英]POST request returning index.html body instead of appropriate response

I've been working on a web app where all the post requests work fine when the frontend is hosted locally through a proxy to the backend, which is hosted on heroku.我一直在开发 web 应用程序,当前端通过后端代理在本地托管时,所有发布请求都可以正常工作,该代理托管在 heroku 上。 However when deploying the frontend (on firebase) the requests still return successfully, but instead of {success: true} it returns the index.html file from the build directory, and does perform any actions on the database.但是,在部署前端(在 firebase 上)时,请求仍然成功返回,但不是 {success: true} 它从构建目录返回 index.html 文件,并对数据库执行任何操作。

Relevant code on heroku: 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}!`));

Respective frontend function:各前端function:

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);
  };

Output from deployed: <.doctype html><html lang="en"><head>... </html> Output 来自部署: <.doctype html><html lang="en"><head>... </html>

Output from localhost: {"success":true} Output 来自本地主机:{“成功”:true}

Ok, I managed to solve this issue by making the route in the fetch to be nameofproject.herokuapp.com/updateBoard since apparently the proxy did not work once the app was deployed.好的,我设法通过将 fetch 中的路由设置为 nameofproject.herokuapp.com/updateBoard 来解决这个问题,因为显然代理在部署应用程序后不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM