Programming :  Student Freelance Forum For Work Experience Builders' (CertificationPoint) The fastest message board... ever.
 
NodeJS Express API, only the live server is responding with: Response to preflight request doesn't pass access control check
Posted by: adcertpoint (Moderator)
Date: July 22, 2021 07:22PM

There are a ton of CORS questions like this and I think I've been through most of them. I'm only asking because none of those solutions have worked.

I am running into the following:

Access to fetch at 'https://myapi.azurewebsites.net/email' from origin 'https://myfrontend.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The CORS preflight request only seems to be happening after I've deployed the api to a live site. When making the request from [myfrontend.net] to [localhost] (api running locally), it works. If it matters, the api is deployed in Azure DevOps.

API:

const cors = require("cors"winking smiley;
const express = require("express"winking smiley;

const { router: emailRouter } = require("./email"winking smiley;

const app = express();

//CORS
app.use(
cors({
origin: "[myfrontend.net"];,
})
);

app.use("/email/", emailRouter);

app.use("/", (req, res) => {
return res.status(200).json({ message: "Server is running" });
});

app.use("*", (req, res) => {
return res.status(404).json({ message: "Not Found" });
});

app.listen(process.env.PORT || 8080, () => {
console.log(`Your app is listening on port 8080`);
});

API POST Route:

const express = require("express"winking smiley;
const router = express.Router();

const cors = require("cors"winking smiley;
const bodyParser = require("body-parser"winking smiley;
const jsonParser = bodyParser.json();

const { emailService } = require("./emailService"winking smiley;

router.post("/", jsonParser, (req, res) => {
console.log("hit", req.body);
if (Object.keys(req.body).length !== 0) {
emailService(req.body).catch(console.error); // this just sends an email using nodemailer
} else {
res.json("Not sent"winking smiley;
}
});

module.exports = { router };

Front End code for the POST request:

export const sendMail = (payload) => {
const url = "[myapi.azurewebsites.net];;

fetch(url, {
method: 'POST',
headers: { "Content-Type": "application/json"},
body: JSON.stringify(payload)
}).then(function (response) {
return response.json();
}).then(function (response) {
console.log(response)
});

}

I have the unmodified code listed when the issue first came up.

Options: ReplyQuote


Sorry, only registered users may post in this forum.
This forum powered by Phorum.