axios preflight http status code 500 - javascript

I can't seem to make the yelp API work for me. I get past the first ajax but the I get error on the second.
XMLHttpRequest cannot load https://api.yelp.com/v3/businesses/search. Response for preflight has invalid HTTP status code 500
I am running this on localhost:3000 and I'm using Allow-Control-Allow-Origin: * extension on Chrome.
This is my code on client side:
axios({
method: 'post',
url: 'https://api.yelp.com/oauth2/token',
data: 'grant_type=client_credentials'
+ '&client_id='+api[0]
+ '&client_secret='+api[1]
}).then(res => {
USER_TOKEN = res.data.access_token;
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(api[2], { headers: { Authorization: AuthStr } })
.then(res => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
})
.catch((error) => {
console.log('error ' + error);
});

Related

Adding Cookie to Request Header of a Fetch API

The issue I have is Cookie is not added to the request header therefore I receive a 403 status. To explain further I am implementing a system link where when a user opens a page, a request token is is fetched and added to the META of the html and also saved in the document.cookie. When the user decides to login, the fetch request below fetchSignIn should automatically add a cookie because I am setting credentials: "include" but it doesn't. I have looked at other examples but I don't understand where my implementation is wrong.
Login implementation using OOP
class Login {
// Private methods...
fetchSignIn (obj, url) {
console.log("Cookie ", document.cookie);
fetch(url, {
method: "POST",
mode: "cors",
credentials: "include",
body: JSON.stringify(obj),
headers: {
"Content-Type": "application/json",
"Authorization": "",
"X-XSRF-TOKEN": getQSelector('meta[name="_csrf"]').content
}
})
.then((response) => response.text())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error('Error: ', error.message);
});
}
}
Fetch token on opening of the page
window.addEventListener("DOMContentLoaded", (e) => {
_loadCSRF(CSRFDOMLOAD);
})
const _loadCSRF = (path) => {
fetch(path) // GET Request
.then((response) => response.json())
.then((data) => {
console.log(data);
document.cookie = data.headerName + "=" + data.token;
getQSelector('meta[name="_csrf_header"]').setAttribute("content", data.headerName);
getQSelector('meta[name="_csrf"]').setAttribute("content", data.token);
})
.catch((err) => console.error("Failed csrf fetch ", err));
}

Fetch requests for token not passed to next fetch request, 401 returned

I'm reaching out to an endpoint with fetch to get a bearer token that will then be used in another fetch request for authentication. I've used Postman first and verified that the endpoints I'm accessing are working, however with my fetch requests below I get a 401.
I have checked in the console that the Authorization is updated after the first fetch and it's passed to the second however I continue to get a 401.
The first call reaches to ./auth and a bearer token is returned. That token is passed off to the next fetch request and but I am getting a 401.
What am I missing or doing wrong, a second pair of eyes could help.
const token = "./auth";
const listings = "./listings";
let clientHeaders = new Headers();
let raw = JSON.stringify({
email: "fake#account.com",
password: "12345",
});
clientHeaders.append("Authorization", "");
clientHeaders.append("Content-Type", "application/json");
clientHeaders.append("Cookie", "");
let req = {
method: "POST",
headers: clientHeaders,
body: raw,
redirect: "follow",
};
fetch(token, req)
.then((response) => response.json())
.then((result) => {
return fetch(listings, {
method: "GET",
headers: {
Authorization: result.token,
"Content-Type": "application/json",
},
});
})
.then((response) => {
return response.json();
})
.then((data) => {
console.log(JSON.parse(data));
})
.catch((error) => {
console.log("error: ", error);
});
You likely need to include the literal word "Bearer" and a space preceding the token in the header:
{
Authorization: `Bearer ${result.token}`
}
// or
{
Authorization: "Bearer " + result.token
}

Axios get request response with 403 error forbidden

I'm new in react . Trying to make "get" request and getting 403 error forbidden, "Response for preflight does not have HTTP ok status.". In network tab in Request Method instead of "get" method shows "options". What could be the problem? Cors already open , problem with token
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer + ${token}`,
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
that's how I'm saving token. May be I'm not correctly saving it in localStorage? But when console.log it displays fine
event.preventDefault()
const formdata = new FormData()
formdata.append("username", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
axios
.post("http://dev.****************/get-token", formdata)
.then(res => {
if (res.data) {
console.log(res.data)
localStorage.setItem("token", res.data.access_token)
localStorage.setItem("updToken", res.data.update_token)
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})
I see a problem in your Bearer token
you write it:
Authorization: `Bearer + ${token}`
but it should be :
Authorization: `Bearer ${token}`,
and the full answer is :
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
Do it like this:
let token = localStorage.getItem("token")
axios.defaults.headers.common['Authorization'] = token
axios
.get("http://dev.*****************get-template")
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
This is due to CORS issue.
To solve this you need to set Access-Control-Allow-Origin header on your server side, allowing the domain from which you are sending the request or you can set it to *

Wp-login.php not signing in user

let formData = [];
formData.push('log=' + encodeURIComponent(username) + '&pwd=' + encodeURIComponent(password) + '&wp-submit=Log+In&testcookie=1');
await fetch(window.location.origin + '/wp-login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData[0],
}).then((res) => {
console.log(res);
window.location.reload();
}).catch((error) => {
console.error(error);
});
The fetch returns 200 response whenever I post to wp-login.php so I am not sure what is wrong here. Status Code is also 302 whenever there is a successful login but mine is 200.

Axios not passing headers on requests

I'm building a VueJS application and I'm using JSON web tokens as my auth system. When I log the user, I store the token with localStorage and works fine. I check the headers and it's in the 'Authorization' param.
I pass with axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')
I see the headers and it's okay. But when I execute a get request to an protected route in my API, return 'unauthorized'. But when I pass the header with token manually in the request, works fine.
Somebody know how to pass the header automatically when executing some request?
try this..
//in get request
const auth = {
headers: {Authorization:'JWT ' + localStorage.getItem('token')}
}
axios.get('http://yourapi.com',auth).then(result => {
console.log(result.data)
})
//in post request
const auth = {
headers: {Authorization:'JWT ' + localStorage.getItem('token')}
}
//note:auth will be 3rd parameter in post request
axios.post('http://yourapi.com',{somekey:'some value'},auth).then(result => {
console.log(result.data)
})
You can use axios.create to create a new axios instance with a config object, including the headers. The configuration will be used for each subsequent calls you make using that instance.
Something like this worked for me:
var App = Vue.component('app', {
mounted () {
this.response = null
this.axiosInstance = axios.create({
baseURL: 'http://localhost:5000/',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
})
},
data () {
return {
response: this.response,
}
},
methods: {
login () {
this.axiosInstance.post('login', {username: 'test', password: 'test'})
.then(resp => {
this.accessToken = resp.data.access_token
this.axiosInstance.defaults.headers['Authorization'] = 'Bearer ' + this.accessToken
})
.catch(err => this.response = err.response.status + ' ' + err.response.statusText)
},
protected () {
this.axiosInstance.get('protected')
.then(resp => this.response = resp.data)
.catch(err => this.response = err.response.status + ' ' + err.response.statusText)
}
},
template: '<div><button #click="login">Connect</button><button #click="protected">Protected</button></div>'
})
interceptor which includes your auth token in every request as an Authorization header:
axios.interceptors.request.use(
function(config) {
const token = localStorage.getItem('token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
},
function(error) {
return Promise.reject(error)
}
)
you could place it in the main file, for example main.js
Check whether server get token from header of "Authorization"
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token')
if No. 2 works, then you may want to execute apis even if web is refreshed, then follow:
axios.interceptors.request.use(function (config) {
const token = 'Bearer ' + localStorage.getItem('token');
config.headers.Authorization = `Bearer ${token}`;
return config;
});
For me issue was with capital Headers vs headers.
Should be lower case. My IDE got me the wrong autocomplete (i.e. with capital H)
This works:
await axios.get(url, {
headers: { 'x-custom-header': 'super header value' }
});
This doesn't!
await axios.get(url, {
Headers: { 'x-custom-header': 'super header value' }
});

Categories

Resources