Before uploading my code to Heroku, my API calls worked just fine. However, it returns a status code of 503 (Service Unavailable)
after deployment.
This is my code
app.js file in my root folder (server file)
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"));
My react file, where the API calls were made
const handleFormSubmit = async (e, val) => {
const { data } = await Axios.post("/post-result", { val });
}
package.json file
{
"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"
}
}
Error log in the console
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)
CodePudding user response:
Option 1 :
Maybe you should try using all the url instead of Axios.post("/post-result",{..}) You can use local variable to determine if you are in Prod or in local environment, create in util folder a file called for example baseUrl.js :
const baseUrl = process.env.NODE_ENV === "production"
? "https://[your url used in port]"
: "http://localhost:[your port]";
export default baseUrl;
And then import baseUrl in your folder and replace your Axios request by :
const { data } = await Axios.post(baseUrl "/post-result", { val });
Option 2 :
Also I noticed that you don't allow any URL in Cors Options :
let corsOptions = {
origin: ["URL ALLOWED", ...],
};
app.use(cors(corsOptions));