Error: Response for preflight has invalid HTTP status code 401 - javascript

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

Related

Network error with Reed API fetch request & basic auth

I am trying to make a request to the REED jobs API although I am getting the error: TypeError: NetworkError when attempting to fetch resource. The call is being made in a React component. The Reed API states You will need to include your api key for all requests in a basic authentication http header as the username, leaving the password empty. This is the part that confuses me and I do not know how to configure the fetch in this way. To help with this, I have sent the API call from Postman and have managed to get response successfully. Because of this, I used the code generation function of Postman to make the below call, but it does not work:
var myHeaders = new Headers();
myHeaders.append("Authorization", `${process.env.REACT_APP_REED_KEY}==`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
Update:
I have changed the code to the below. Unfortunately, I am still getting an error. I am also now getting a new error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15. (Reason: CORS preflight response did not succeed).
Updated code:
import { encode } from "base-64";
var myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${encode(process.env.REACT_APP_REED_KEY)}`);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("https://www.reed.co.uk/api/1.0/search?keywords=accountant&location=london&employerid=123&distancefromlocation=15", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));

How to allow Request header field access-control-allow-origin on VueJS

I trying to make a POST request to Slack API using raw JSON but I keep getting the error below
Access to XMLHttpRequest at 'https://hooks.slack.com/services/conuation/of/the/url' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
Below is code
const params = {
"attachments":[
{
"fallback":"New Project Lead:<" + this.our_website + "|Click here to view>",
"pretext":"New Project Lead:<" + this.our_website + "|Click here to view>",
"color":"#D00000",
"fields":[
{
"title":"Company",
"value":this.user_company,
"short":false
},
{
"title":"Country",
"value":getName(this.user_country),
"short":false
}
]
}
]
};
this.axios.post('https://hooks.slack.com/services/continuation/of/url', params, {
headers: {
'content-type': 'application/json',
'Access-Control-Allow-Origin' : '*',
},
}).then((response)=>{
loader.hide();
let msg = "Sent Successfully";
this.displayAlert("Done", msg, "success");
setTimeout(() => { // redirect to home after 2s
document.location = '/';
}, 2000);
}).catch((error) =>{
alert(error);
});
}).catch((error) => {
loader.hide();
let msg = "Error : " + error;
this.displayAlert("Error", msg, "error");
});
I am using VueJS and Axios HTTP library for the call. Whenever I test with POSTMAN, it works fine.
You can't send this request from frontend to this service. A lot of services block it.
You can create your backend sub service and send request to slack api.
So in result you have your own service with url mydomain.com/services/continuation/of/url, when you call it, your service will make call to https://hooks.slack.com/services/continuation/of/url and return slack response

How to make a get request in Angular to receive Wordpress's Gravityforms data?

I'm trying to receive entries from Gravityform Rest API V.2 in Angular by making a get request, except I keep getting 401 http error responses, while my console logs ('Access to XMLHttpRequest at 'livesite' from origin 'localsite' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.'). I have used 'basic authentification' to make the request.
https://docs.gravityforms.com/rest-api-v2/#basic-authentication
https://docs.gravityforms.com/rest-api-v2/#get-forms-form-id-entries
I succesfully used the Postman application to make post/get requests with the same credentials. I have added SSL to my domain and allowed "Access-Control-Allow-Origin: *" in Wordpress.
// Link to form #1
const url = 'https://livesite.com/wp/wp-json/gf/v2/forms/1/entries';
// Base64 key with : and keys are set in environment.ts
const key = btoa(this.publicApiKey + ':' + this.privateApiKey);
// Create HttpHeaders
const headersObject = new HttpHeaders().set('Authorization', 'Basic ' + key);
const httpOptions = { headers: headersObject };
// Get
this.http.get(url, httpOptions)
.subscribe(
response => {
console.log('response', response);
},
error => {
console.log('error', error);
}
);

CORS : OPTIONS 500() : Failed to load header

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

isomorphic-fetch: Failed to fetch

When I open a POST request, it doesn't work well, what's wrong with my code?
Btw. I send a POST request,but server received an OPTIONS request.
try{
const URL = config.LOGIN;
const data = await fetch(URL,{
method:"POST",
headers:{
"Accept": "application/json",
"Content-Type": "application/json"
},
body:JSON.stringify({
"a":1,
"b":2
})
}).then((response)=>{
return response.json();
});
console.log(data)
}catch(e){
// TypeError: Failed to fetch
alert(e)
}
And browser reports an error: 405: Method Not Allowed
GET request works fine
const data = await fetch(URL).then((res)=>{
return res.json()
});
Client:
405: Method Not Allowed
TypeError: Failed to fetch
Server:
[W 170505 14:20:00 web:1971] 405 OPTIONS /shundai/CoffeeManagementLogin (192.168.2.114) 1.00ms
Thanks!

Categories