I'm making an API request to the Beehiiv API, to get my list of publications.
Inside my React component, I've set up a fetch request to the API. However the request is being being blocked by the CORS policy. Request code below:
async function makeRequest(){
const fetchOptions = {
method: 'get',
headers: {
"X-ApiKey": '<MY API KEY>',
"Content-Type": "application/json",
"Access-Control-Allow-Origin" : '*'
},
}
fetch('https://api.beehiiv.com/v1/publications', fetchOptions).then( response => response.json() )
.then( data => console.log(data) )
}
makeRequest();
The response in the console is as follows:
Access to fetch at 'https://api.beehiiv.com/v1/publications' from origin 'http://localhost:3000' 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.
Calling other API's does not seem to result in getting blocked.
Any ideas on why this may be happening? Please let me know! Thanks!
CodePudding user response:
From beehiiv API documentation:
API keys are considered sensitive data and should not be shared with anyone. Be careful not to expose the API key in your source code or any other public location (including front-end code).
The API isn't supposed to be called from the frontend.
You need to make AJAX requests to your own server, which then calls the API, so the API key isn't exposed.
CodePudding user response:
try using ''no-cors' mode.
fetch('url', {
mode: 'no-cors',
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(obj)
})