I am trying to fetch information from DHL API but it keeps getting blocked by cors policy.
I have cors policy set up in my backend server, but still, it is causing an error
what am I doing wrong?
this is the error I am getting: "Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response."
backend:
app.use(cors({
origin:["http://localhost:3000"],
method:["GET","POST","OPTIONS","PUT"],
credentials: true,
}));
app.get("https://api-eu.dhl.com/track/shipments", (req,res) => {
res.send({msg:ok})
})
front end:
const trackBtn = () => {
fetch(`https://api-eu.dhl.com/track/shipments`, {
method: 'GET',
params: {trackingNumber: '423432432'},
headers: {
'Accept': 'multipart/form-data',
'DHL-API-Key': 'apF7cO8oD2hN7v',
'Content-Type' : 'multipart/form-data charset=UTF-8',
'Access-Control-Allow-Credentials':'*',
"Access-Control-Allow-Methods":"DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
},
}).then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
CodePudding user response:
Remove the Access-Control-Allow-*
headers from your request. They belong in the response, that is, are added by the server. You must not include them in a request.
You must also allow the non-standard header DHL-API-Key
in your CORS enablement:
app.use(cors({
origin:["http://localhost:3000"],
method:["GET","POST","OPTIONS","PUT"],
credentials: true,
allowedHeaders: ["DHL-API-Key"]
}));
Lastly, params
is not an allowed option for fetch
, perhaps you mean
fetch(`https://api-eu.dhl.com/track/shipments?trackingNumber=423432432`, ...)