CORS : OPTIONS 500() : Failed to load header - javascript

I have a problem with CORS. I can do a GET request but it's impossible to do a POST or PUT Request.
I use AWS API GateWay to do my API. My APi works with postman.
I have these errors: error 500
My code :
postUsersHTTP(request:any): Promise<Response> {
let headers = new Headers({
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT",
"Access-Control-Allow-Headers": "X-Custom-Header"
});
let options = new RequestOptions({ headers: headers });
return this._http.post(environment.baseURL + "/user", request, options).toPromise()
.then(this.extractData)
.catch(this.handleErrorPromise);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
private handleErrorPromise (error: Response | any) {
console.error(error.message || error);
return Promise.reject(error.message || error);
}
I see a lot of answer on stackoverflow but not reallly usefull for my error Thanks !

I've been there, I've done that!
that's call X-Scripting protection.
Install this extension to your Chrome, and you'll be good to go.
Allow-Control-Allow-Origin: *
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Related

Netlify function: GitHub API proxy request fails with `error decoding lambda response: json`

This Netlify function should run as an endpoint on example.com/.netlify/functions/github and is supposed to proxy a fetch request from my website, reach out to the GitHub API and send data back to the website.
As far as I have understood, I can use to GET data from the GitHub API without authentication. Hitting their API directly in the browser works: https://api.github.com/orgs/github/repos?per_page=2 (also works from Postman).
The data is an array of objects where each object is a repository.
There has been multiple issues the past couple of years where Netlify functions (running on AWS lambdas) have had hickups that resulted in error messages similar to mine, so I'm confused whether this is an error in my code or something weird on their side.
First, the proxy function which – according to the Netlify admin console – runs without error. In a support article Netlify requires the result returned as JSON.stringify(), so I follow that convention here:
const fetch = require('node-fetch')
const url = 'https://api.github.com/orgs/github/repos?per_page=2'
const optionsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type'
}
const fetchHeaders = {
'Content-Type': 'application/json',
'Host': 'api.github.com',
'Accept': 'application/vnd.github.v3+json',
'Accept-Encoding': 'gzip, deflate, br'
}
exports.handler = async (event, context) => {
if (event.httpMethod === 'OPTIONS') {
return {
'statusCode': '200',
'headers': optionsHeaders,
}
} else {
try {
const response = await fetch(url, {
method: 'GET',
headers: fetchHeaders
})
const data = await response.json()
console.log(JSON.stringify({ data }))
return {
statusCode: 200,
body: JSON.stringify({ data })
}
} catch (err) {
console.log(err)
}
}
}
Client fetch that hits https://example.com/.netlify/functions/github. URL is correct, the function is executed (verified that in the Netlify admin panel):
const repos = document.querySelectorAll('.repo')
if (repos && repos.length >= 1) {
const getRepos = async (url) => {
try {
const response = await fetch(url, {
method: "GET",
mode: "no-cors"
})
const res = await response.text()
// assuming res is now _text_ as per `JSON.stringify` but neither
// that nor `.json()` work
console.log(res[0].name)
return res[0].name
} catch(err) {
console.log(err)
}
}
const repoName = getRepo('https://example.com/.netlify/functions/github')
repos.forEach((el) => {
el.innerText = repoName
})
}
Not 100% sure where this error message originates from, it is probably not the console.log(err) although it displays in the browser console, because the error code is 502 and the error also shows up directly in the response body in Postman.
error decoding lambda response: error decoding lambda response: json: cannot unmarshal
string into Go value of type struct { StatusCode int "json:\"statusCode\""; Headers
map[string]interface {} "json:\"headers\""; MultiValueHeaders map[string][]interface {}
"json:\"multiValueHeaders\""; Body string "json:\"body\""; IsBase64Encoded bool
"json:\"isBase64Encoded,omitempty\""; Metadata *functions.Metadata
"json:\"metadata,omitempty\"" }
Haven't found any clear information on this issue, could any of you enlighten me?
The only response that don't comply with the schema is the preflight request. From the error message, I assume you need to change:
'statusCode': '200',
to
'statusCode': 200, // StatusCode int
Even better, because there's no content, you may want to use 204 instead.
If that's still not enough, I may still want to include the body there as well, as it doesn't seem optional:
return {
'statusCode': 204,
'headers': optionsHeaders,
'body': ''
}

how to get response header in angular 8

Hey i have implemented an api which is a GET request
now what i want is Response Header values but only some of them are showing in the api reponse but in network tab every value is showing
i dont know what is the problem
this is my Http service
pendingResultData(payload: Payload, headerConfig?: {}) {
const params = payload
? {
type: payload.type,
data_scopes: payload.data_scopes,
observe: 'response',
...headerConfig
}
: { observe: 'response', ...headerConfig };
const reqUrl = '/api/data_capture';
return this.timerService.timer(this.httpService.getFullResponse(reqUrl, params));
}
this is my interceptor
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.idToken = this.authService.getAccessToken() || '';
// cloning original request and set/add new headers
const authReq = req.clone({
headers: this.idToken
? req.headers
.set('Authorization', `Bearer ${this.idToken}`)
.set('Access-Control-Allow-Origin', '*')
.set('Content-Type', 'application/json')
.set("Access-Control-Expose-Headers", "*")
: req.headers,
params: req.params
});
return next.handle(authReq);
}
now the headers are coming in response header you can see in Screen shot
i want total, current-page, per-page but headers i am getting in api response are
headers: "content-length: 194
content-type: application/json; charset=utf-8
cache-control: max-age=0, private, must-revalidate"
i wanna know am i doing something wrong and if this a backend problem or not?
any help?
thanks
You can access these by user response.headers.get() method. e.g:
this.httpService.getFullResponse(reqUrl, params).subscribe(response=> {
console.log(response.headers.get('per-page'));
});
i think you have to add your custom headers to "access-control-expose-headers" in the backend response. In your screenshot from above it looks that their are not in the list.
(https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers)
https://github.com/angular/angular/issues/5237#issuecomment-441081290

Error: Response for preflight has invalid HTTP status code 401

I am getting errors that XMLHttpRequest cannot load "http://apiurl/signup" Response for preflight has invalid HTTP status code 401 and OPTIONS 401 Unauthorized
CORS is enabled in Server Side and in browser.
I am new to Angular 2
Http Service Code
signup(form : any)
{
const body = JSON.stringify(form);
console.log("HTTP",body);
const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
,'Authorization':'Basic <key>'
});
let options = new RequestOptions({headers : headers});
return this.http.post('http://--/signup',body,options).map((data:Response) => data.json())._catch(this.handleError).subscribe(
err => this.logError(err),
() =>console.log('Authentification Complete')
);
}
logError(err) {
console.error('There was an error: ' + err);}

Request header field If-None-Match is not allowed by Access-Control-Allow-Headers in preflight response

I am receiving the following error when posting to a REST API using dojo/store/JsonRest.
I am using "X-Requested-With": null in order to avoid preflight request but I still receive this error.
API fully support CORS.
Any idea how can be fixed?
Request header field If-None-Match is not allowed by
Access-Control-Allow-Headers in preflight response.
var store = new JsonRest({
target: 'https://api.xxx.com/data',
headers: {
"Authorization": 'Bearer ' + 'd4c72611fc43ab44a46344d907a2b96964df2c91',
"X-Requested-With": null // no prefligh
}
});
store.get('1-00').then(function (data) {
// ok works here
console.log('get', data)
});
// post request
store.add({name:'test'}).then(function (data) {
// error here
console.log('add', data)
});
I was able to solve this issue using "If-None-Match": null in the headers for JsonRest.
Interesting doc regarding "If-None-Math" can be found on HTTP/1.1 spec.
var store = new JsonRest({
target: 'https://api.xxx.com/data',
headers: {
"Authorization": 'Bearer ' + 'd4c72611fc43ab44a46344d907a2b96964df2c91',
"X-Requested-With": null`, // no prefligh
"If-None-Match": null // solve my issue
}
});
store.get('1-00').then(function (data) {
// ok works here
console.log('get', data)
});
// post request
store.add({name:'test'}).then(function (data) {
// ok works here
console.log('add', data)
});

Fetch answer empty due to the preflight?

I have an webapp react.js / redux / webpackt / es6... and an api in go with mux from gorilla.
When I make call with the function below my header is empty and content too.
I'm using this package in my webapp to make calls
"isomorphic-fetch": "^2.2.1",
My call example
export function Login(userData) {
return dispatch => {
fetch(API + '/login', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: userData.email,
password: userData.password,
}),
})
.then(response => {
console.log(response);
console.log(response.statusText);
console.log(response.status);
console.log(response.headers);
console.log(response.headers.get("Authorization"));
console.log(response.json());
return response.json()
if (response.status >= 200 && response.status < 300) {
console.log(response);
dispatch(LoginSuccess(response));
} else {
const error = new Error(response.statusText);
error.response = response;
dispatch(LoginError(error));
throw error;
}
}).then(function(json) {
console.log('parsed json' + json)
})
.catch(error => { console.log('request failed', error); });
}
In the beginning I had a problem with cors How to handle preflight CORS requests on a Go server I used this solution
We can look the call inside of the console :
login OPTIONS 200 fetch auths.actions.js:38 352 B 1 ms
login POST 200 json Other 567 B 82 ms
When I look inside of my POST Header response I have :
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin: http://localhost:3000
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE0NTQ3NTcxNjEsInVzZXJfaWQiOiI1NmI1YjZlOTFhZTMzYjAwMDFhYmE1MTQifQ.WGoTMxm6OuN24Olwr93J3pND9dFLCtG5MyiRbqLWeD244JtDzq0bGgQMixeZxyuxwGK3u8KhyWD7Rr6iZAGNpA
Content-Type: application/json
Date: Sat, 06 Feb 2016 11:12:41 GMT
Content-Length: 2
So the response handle my preflight information not my POST ? Because there is nothing inside of the response.headers and response.headers.get("Authorization")
There is something wrong ?
I had the problem that my headers were sent, correctly received (chrome's network tab correctly shows me all the sent headers), but I couldn't access them in js (response.headers was empty). As described in Fetch get request returns empty headers, this happened because the server did not set the Access-Control-Expose-Headers header, resulting in the needed headers not to be exposed to js.
So the solution is to add this header on the server and voilà, now the headers are accessible in js:
Access-Control-Expose-Headers: <header-name>, <header-name>, ...
The header takes a comma-separated list of header-names to be exposed to the browser.
For additional info on why this header is needed, see Why is Access-Control-Expose-Headers needed?

Categories