【问题标题】:Axios API calls are not working after deploying the web application on Heroku - MERN Application在 Heroku 上部署 Web 应用程序后,Axios API 调用不起作用 - MERN 应用程序
【发布时间】:2023-03-16 02:22:01
【问题描述】:

在将我的代码上传到 Heroku 之前,我的 API 调用运行良好。但是,它在部署后返回状态码503 (Service Unavailable)。 这是我的代码

我的根文件夹中的 app.js 文件(服务器文件)

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).then(() => console.log("Connected to db!")).catch(dbErr => console.log(dbErr));

app.use(express.json());
app.use(cors());

app.post("/post-result", async (req, res) => {
    console.log(req.body.val);
    const newSurvey = new survey({ surveyValues: req.body.val });


    await newSurvey.save()
        .then(data => {
            res.send(newSurvey);
            console.log(newSurvey);
        }).catch(err => console.log(err));
});

app.get("/results", async (req, res) => {
    const result = await survey.find({});
    res.send(result);
});

if (process.env.NODE_ENV === "production") {
    app.use(express.static(path.join(__dirname, "/client/build")));
    app.get("*", (req, res) => {
        res.sendFile(path.join(__dirname, "client", "build", "index.html"));
    })
} else {
    app.get("/", (req, res) => {
        res.send("API running");
    })
}

app.listen(process.env.PORT, () => console.log("Listening on PORT 8080"));

我的反应文件,API 调用的地方

const handleFormSubmit = async (e, val) => {
    const { data } = await Axios.post("/post-result", { val });
}

package.json 文件

{
  "scripts": {
    "start": "nodemon app.js",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "mongoose": "^6.0.12"
  }
}

控制台中的错误日志 Uncaught (in promise) Error: Request failed with status code 503 at e.exports createError.js:16) at e.exports (settle.js:17) at XMLHttpRequest.S (xhr.js:66)

【问题讨论】:

    标签: node.js api heroku mern http-status-code-503


    【解决方案1】:

    选项 1:

    也许您应该尝试使用所有 url 而不是 Axios.post("/post-result",{..}) 您可以使用局部变量来确定您是在 Prod 还是在本地环境中,在 util 文件夹中创建一个名为 baseUrl.js 的文件:

     const baseUrl = process.env.NODE_ENV === "production"
        ? "https://[your url used in port]"
        : "http://localhost:[your port]";
    export default baseUrl;
    

    然后在您的文件夹中导入 baseUrl 并将您的 Axios 请求替换为:

     const { data } = await Axios.post(baseUrl + "/post-result", { val });
    

    选项 2:

    我还注意到您不允许在 Cors 选项中使用任何 URL:

    let corsOptions = {
      origin: ["URL ALLOWED", ...],
    };
    
    app.use(cors(corsOptions));
    

    【讨论】:

    • 非常感谢。它有效!
    • 欢迎您,祝您好运!
    猜你喜欢
    • 1970-01-01
    • 2018-08-07
    • 2021-04-06
    • 1970-01-01
    • 2021-10-31
    • 2021-10-29
    • 2020-09-08
    • 2020-06-05
    • 2020-08-18
    相关资源
    最近更新 更多