inserting header axios async thunk - javascript

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?

Related

CORS Policy Error when attempting to POST to Twilio API

From a VueJS application I'm attempting to do a simple POST to the Twilio API in order to send an SMS. When the POST is executed I receive the following error:
"Access to XMLHttpRequest at 'https://api.twilio.com/2010-04-01/Accounts/AC42exxxxxxxxxxcfa9c48/SMS/Messages' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field username is not allowed by Access-Control-Allow-Headers in preflight response."
The offending code is the following:
sendTwilio(){
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const sFromNumber = process.env.TWILIO_NUMBER;
const sBaseURL = 'https://api.twilio.com';
const phoneNumber = parsePhoneNumberFromString(this.sms.to_number,'US')
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`,
'username': `${accountSid}`
},
sBodyText='Test'
this.SmsUrl = sBaseURL + '/2010-04-01/Accounts/' + accountSid + '/SMS/Messages';
if (phoneNumber.isValid()){
this.sms.formattedPhone = phoneNumber.number;
this.postData = 'From=' + sFromNumber
+ '+To=' + phoneNumber.number
+ '+Body=' + sBodyText
axios.post(`${this.SmsUrl}`, this.postData, {
headers: headers
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
},
Is the problem with the format used for the username in the header or something with my CORS settings?
My CORS settings are as follows:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = [
'http://localhost:8000',
'http://localhost:8080',
'http://127.0.0.1:8000'
]
Twilio uses Basic Auth to do authentication, so in your case when doing your POST using axios you need to do:
const headers = {
'Content-Type': 'application/json'
};
const auth = {
username: accountSid,
password: authToken
}
[...]
axios.post(this.SmsUrl, this.postData, {
auth: auth,
headers: headers
})
I'm not sure how you're using this though. Have a look at the comments of the question. You should never expose your Twilio credentials to the client in a browser application.

Cloud function post cors issue

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)
}))
})

Custom http Header breaks CORS

My API has following CORS setup:
(I am the owner, I can change these settings)
Middleware function:
// HeaderMiddleware ...
func HeaderMiddleware(next httprouter.Handle) httprouter.Handle {
return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-APIKEY")
// ! Production
// if r.Header.Get("X-APIKEY") != "fdfdsf5df6d541cd6" || r.RemoteAddr != frontendURL {
// w.WriteHeader(http.StatusForbidden)
// json.NewEncoder(w).Encode(NoContentResponse{Success: false, Error: "You aren't allowed to request the api here."})
// return
// }
// ! Production
next(w, r, p)
})
}
The X-APIKEY header is not necessary yet, a request without it just works fine:
fetch('http://localhost:8013/tobi#gmx.at/usage', { headers: { } })
.then(response => response.json())
.then(console.log)
returns {used: false} (expected response)
However, if I add the X-APIKEY header:
fetch('http://localhost:8013/tobi#gmx.at/usage', { headers: { 'X-APIKEY': 'sdfsdfsafsf' } })
.then(response => response.json())
.then(console.log)
following error is thrown:
Access to fetch at 'http://localhost:8013/tobiwibu#gmx.at/usage' from origin 'http://localhost:8080' 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.
If I do the request with the X-APIKEY header in Postman, it says that the Access-Control-Allow-Origin header is sent along:
P.S.: I already tried other headers, it works!
If I do the request with chrome (without X-APIKEY header), the Access-Control-Allow-Origin header is sent.
Thanks for your help!
I've now fixed it like this:
I misuse the http Accept header for my API-Token.
Example:
fetch('http://10.0.0.11:8013/lopm#htl/usage',
{"headers":{ "Accept": "fdfdsf5df6d541cd6++" }})
.then(response => response.json())
.then(console.log)
Of course, this isn't a really nice solution, but it does its job.
Thanks for all of you for giving me helpful tips!

Django Rest Framework CORS blocking XMLHttpRequest

I have set up my CORS policy using Django-cors-headers with the following settings:
APPEND_SLASH=False
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'localhost:3000',
'localhost'
)
I have also added it to installed_apps and middleware.
Now I am making a React app for the front end and using AXIOS for my API requests. When I make an API request to log in to my app the CORS policy allows it. But, if I make an API request that requires a Token, I get:
Access to XMLHttpRequest at 'localhost:8000/api/TestConnection/' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
It seems that I need to allow XMLHttpRequest for supported protocol schemes but I cannot find anything in the pypi documentation about this.
EDIT:
Here is the AXIOS Request:
axios.post("localhost:8000/api/TestConnection/",
{headers:
{
'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
}
},
{
testString: 'Hello API'
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
})
Thank you!
I Have had a similar issue with a ReactNative app which was happening due to ReactNative using IP 10.0.2.2 for localhost (I do not remember the details or why). I solved it by adding to my class.
componentWillMount() {
axios.defaults.baseURL = 'http://10.0.2.2:8000/api/';
axios.defaults.timeout = 1500;
}
I do not know if this is the right IP but may be worth looking at.
EDIT
handleRequest() {
const payload = { username: this.state.username, password: this.state.password }
axios
.post('login/', payload)
.then(response => {
const { token, user } = response.data;
// We set the returned token as the default authorization header
axios.defaults.headers.common.Authorization = `Token ${token}`;
// Navigate to the home screen
Actions.main();
})
.catch(error => {
console.log(error)
});
}
By saving the Token within my headers it is always sent.
The error says "from origin 'http://localhost:3000'" and to "check the cors policy"
I see your CORS policy is
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'localhost:3000',
'localhost'
)
maybe try providing the full http url. so
CORS_ORIGIN_WHITELIST = (
'localhost:8000',
'http://localhost:3000',
'localhost'
)
I solved it! The solution was very simple(of course),
For the request I needed to use part of #HenryM 's solution.
First I needed to establish the default url:
axios.defaults.baseURL = 'http://127.0.0.1:8000/api/';
Then I save the payload and header to const variables:
const header = {
headers:{
'Authorization': "Bearer " + localStorage.getItem('JWTAccess')
}
}
const payload = {
testValue: "Hello API"
}
Finally, the main issue was that my parameters were in the wrong order:
axios.post("TestConnection/", payload, header)
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
Apparently the propper order, at least when using Django Rest Framework, is payload then header!!!
Thank you to everyone who tired to help!
This was the article that ended up helping me: https://www.techiediaries.com/django-vuejs-api-views/

How to use Fetch, CORS headers not working

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 );
}

Categories

Resources