I am getting this error:
"No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'my origin' is therefore not allowed access."
Backend:
after((request, response) -> {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Request-Method", "*");
response.header("Access-Control-Allow-Headers", "*");
response.type("application/json");
});
Frontend:
async req() {
let request_url = ***my url***;
let init = {
method: "post",
body: { **my body content** }
};
const res = await fetch( request_url , init );
}
Related
I have the following headers setup in my node js api app:
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested, Content-Type, Accept Authorization"
);
if (req.method === "OPTIONS") {
res.header(
"Access-Control-Allow-Methods",
"POST, PUT, PATCH, GET, DELETE"
);
return res.status(200).json({});
}
next();
});
With this config I can send GET, POST request to my api hosted in heroku from Postman.
But when I try from my frontend app built with vue. I get the following error.
And I'm using fetch to send the request to remote api:
async signup() {
try {
const formData = new FormData();
formData.firstName = this.firstName;
formData.lastName = this.lastName;
formData.email = this.email;
formData.password = this.password;
formData.confirmPassword = this.password;
formData.mobile = this.mobile;
formData.gender = this.gender;
formData.profileImg = this.profileImg;
const response = await fetch(
"https://api-url.com/auth/patient/signup",
{
body: formData,
method: "POST",
}
);
const data = await response.json();
this.response = JSON.stringify(data);
} catch (error) {
console.log(error);
}
}
Can anyone point the mistakes I've made here ?
I think you need to set the headers in the fetch call. I see that you have already added body and method.
headers: { 'Content-Type': 'application/json' }
I'm trying to set apikey in the header of req-- it gives me Cors error when done locally,
though when done on postman it goes through
export const fetchCreativeAd = createAsyncThunk(
'creativeAd/fetchCreativeAd',
async (payload, thunkAPI) => {
try {
const urlParam = process.env.NEXT_PUBLIC_AWS_ENDPOINT;
const response = await axios.get(
`${urlParam}/creative_ad?product_name=${payload.productName}&product_description=${payload.productDescription}&platform=${payload.platform}&audience=${payload.audience}&ad_tone=${payload.adTone}`,
{
headers: {
'x-api-key': `${process.env.NEXT_PUBLIC_AWS_API_KEY}`,
},
}
);
res.data.headers['x-api-key'];
console.log(process.env.NEXT_PUBLIC_AWS_API_KEY);
return response;
} catch (error) {
return thunkAPI.rejectWithValue({ error: error.message });
}
}
);
Cors error:
Access to XMLHttpRequest at '"urlParam"creative_ad?product_name=asdf&product_description=asdf&platform=asdf&audience=asdf&ad_tone=asdf' 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.
how do I insert the header portion in axios?
Getting the cors error when sending the request, but working in the postman
Error Message:
Access to fetch at (cloud function url) from origin (my web app) has
been blocked by CORS policy: 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.
Cloud Function Code:
exports.add_edit_location_routes = functions.https.onRequest((request, response) => {
let obj = request.body
deletePreviousRoutes(obj.assign_route_id, obj.driver_id, () => addRoutes(obj, (msg) => {
response.send(msg)
}))
})
Request:
fetch("url", {
body: JSON.stringify(json),
method: "POST",
headers: {'Content-Type': 'application/json'},
}).then(res => res.json()).then(obj => console.log(obj))
added this but still not working
res.set('Access-Control-Allow-Origin', '*')
Try including the code you provided in the Cloud Function and not the fetch request.
exports.add_edit_location_routes = functions.https.onRequest((request, response) => {
let obj = request.body
response.set('Access-Control-Allow-Origin', '*')
deletePreviousRoutes(obj.assign_route_id, obj.driver_id, () => addRoutes(obj, (msg) => {
response.send(msg)
}))
})
How do i fix this?
let response = await fetch("https://www.cloudflare.com/cdn-cgi/trace", {
// credentials: 'include',
method: 'GET',
// method: 'POST',
headers: {'Content-Type': 'application/json'}
})
Access to fetch at 'https://www.cloudflare.com/cdn-cgi/trace' from
origin 'http://localhost:3000' has been blocked by CORS policy:
Request header field content-type is not allowed by
Access-Control-Allow-Headers in preflight response.
You can try do it like this:
async function test () {
let response = await fetch("https://www.cloudflare.com/cdn-cgi/trace", {mode: "cors"});
let text = await response.text();
console.log(text)
}
test()
I am trying to access the Amazon market place api. I get the following error,
Failed to load http://completion.amazon.com/search/complete?search-alias=digital-text&client=amazon-search-ui&fb=1&mkt=1&q=trump: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
But I have passed the headers in AWS rest API also I have enabled cores.
function getAmazonDataByKeyWord(keyword, callback) {
console.log('dhfajdkh');
const instance = axios.create({
baseURL: "http://completion.amazon.com",
headers: {
'Access-Control-Allow-Origin': 'http://localhost:9080',
"Access-Control-Allow-Headers": "Content-Type,Authorization",
"Access-Control-Allow-Methods": "PUT, GET, POST, DELETE, OPTIONS",
"Access-Control-Allow-Credentials": true
},
xhrFields: {
withCredentials: false
}
});
instance.defaults.headers["keyId"] = "AKIAI7VIL36475SPDBCA";
instance.defaults.headers["secretKey"] = "ggyvg0je2oYe84WButOYLIO4qy";
instance.defaults.headers["asoTag"] = "nerf0e-20";
instance.defaults.headers["keywordStatsQueue"] = new queue(1, Infinity);
instance.defaults.headers["keywordStatsAnalyzeQueue"] = new queue(1, Infinity);
instance.get("/search/complete?search-alias=digital-text&client=amazon-search-ui&fb=1&mkt=1&q=" + keyword).then(function (res) {
var result = {};
result.status = httpStatus.OK;
result.result = res.data;
console.log('res');
console.log(result);
callback(null, result);
}).catch(function (error) {
console.log(error);
});
}