Axios Bearer token - axios

I'm currently using the following code to acces to test my routes. I can acces the route but it always tells me that there's a error 401
import axios from 'axios';
export const HTTP = axios.create({
baseURL: `http://localhost/rocourt/01-Backend/api/v1/public/`,
headers: {
Authorization: 'Bearer f4eaa1ff05046c01'
}
});
It looks like that from the .vue
import {HTTP} from '../http-common';
export default {
name: 'adresse',
data() {
return {
posts: [],
errors: [],
message: 'test'
}
},
created() {
HTTP.get(`adresses/1`)
.then(response => {
this.posts = response.data;
})
.catch(e => {
this.errors.push(e)
})
}
}
The errors looks like this :

Related

When requesting github to get access token i was getting "not found" error as response

here is the request:(i required node-fetch as fetch to do http requests on the server)
const { code } = req.body;
const data = new FormData();
data.append("client_id", process.env.GITHUB_CLIENT_ID);
data.append("client_secret", process.env.GITHUB_CLIENT_SECRET);
data.append("code", code);
data.append("redirect_uri", process.env.GITHUB_REDIRECT_URL);
fetch(`https://github.com/login/oauth/access_token`, {
method: "POST",
body: data,
headers: {
Accept: "application/json",
},
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err)
})
here is the response:
{ error: 'Not Found' }

Nuxt proxy target not taken into account

When calling an api like below with Axios in Nuxt:
async test() {
await this.$axios
.post(
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
I'm getting the CORS error below in my browser:
Access to XMLHttpRequest at 'https://webservice.foo.com/api-entreprise/enroler/?id=1234' from origin 'http://mywebsite.test:3001' 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.
So, I retried with proxy settings:
nuxt.config.js:
axios: {
proxy: true,
},
proxy: {
'/api123/': {
target:
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
pathRewrite: { '^/api123/': '' },
changeOrigin: true,
},
},
and the call below:
async test() {
await this.$axios
.post(
'/api123/',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
But the proxy target doesn't seem to be used, and I get an error 400 showing http://mywebsite.test:3001/api123/ instead.
Request URL: http://mywebsite.test:3001/api123/
Request Method: POST
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:3001
Referrer Policy: strict-origin-when-cross-origin
What's wrong in my proxy configuration ?
ref. https://axios.nuxtjs.org/options/#proxy

getserversideprops axios return Request failed with status code 404 but it work on useffect

I am fetching a big problem with axios in my project. I used axios for fetching data in getServerSideProps. but is it showing 'Request failed with status code 404', in the same time i also used axios in useEffect where it get data from api.
export async function getServerSideProps() {
try {
const ApiUrl = apiBaseUrl + "/api/my-url";
const homeData = await axios
.get(ApiUrl)
.then((response) => {
return response.data;
})
.catch((error) => {
return error.message;
});
return {
props: {
homeData: homeData, // its is return Request failed with status code 404
error: false,
ApiUrl: ApiUrl,
},
};
} catch (e) {
return {
props: {
error: true,
homeData: null,
message: e.message,
},
};
}
}
through i cna not get data from getServerSideProps i used useEffect
useEffect(() => {
if (typeof props.homeData === "string") {
console.log(props); // it is showing error 'Request failed with status code 404'
} else if (props.homeData) {
console.log(props.homeData);
// setData(props.homeData);
} else {
axios
.get(apiBaseUrl + "/api/my-url")
.then((response) => {
seteData(response.data);
})
.catch((error) => {
console.log(error);
});
}
}, [props]);

Can't make a POST request using axios

The error message I get is
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/user/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
http-header.js
"import axios from 'axios';
export default axios.create({
baseURL: "http://localhost:5000",
headers: {
'Content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
AuthService.js
import axios from '../http-header.js'
export default {
login : user => {
return axios.post('/user/login', user)
.then(res => {
if(res.status !== 401)
return res.json().then(data => data)
else {
return {isAuthenticated: false, user: {username: "", role: ""}}
}
})
}
}
You have to add 'Access-Control-Allow-Origin': '*' to your backend.

Passing headers with axios POST request

I have written an Axios POST request as recommended from the npm package documentation like:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data)
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
And it works, but now I have modified my backend API to accept headers.
Content-Type: 'application/json'
Authorization: 'JWT fefege...'
Now, this request works fine on Postman, but when writing an axios call, I follow this link and can't quite get it to work.
I am constantly getting 400 BAD Request error.
Here is my modified request:
axios.post(Helper.getUserAPI(), {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
},
data
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
When using Axios, in order to pass custom headers, supply an object containing the headers as the last argument
Modify your Axios request like:
const headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {
headers: headers
})
.then((response) => {
dispatch({
type: FOUND_USER,
data: response.data[0]
})
})
.catch((error) => {
dispatch({
type: ERROR_FINDING_USER
})
})
Here is a full example of an axios.post request with custom headers
var postData = {
email: "test#test.com",
password: "password"
};
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
To set headers in an Axios POST request, pass the third object to the axios.post() call.
const token = '..your token..'
axios.post(url, {
//...data
}, {
headers: {
'Authorization': `Basic ${token}`
}
})
To set headers in an Axios GET request, pass a second object to the axios.get() call.
const token = '..your token..'
axios.get(url, {
headers: {
'Authorization': `Basic ${token}`
}
})
const data = {
email: "me#me.com",
username: "me"
};
const options = {
headers: {
'Content-Type': 'application/json',
}
};
axios.post('http://path', data, options)
.then((res) => {
console.log("RESPONSE ==== : ", res);
})
.catch((err) => {
console.log("ERROR: ====", err);
})
All status codes above 400 will be caught in the Axios catch block.
Also, headers are optional for the post method in Axios
You can also use interceptors to pass the headers
It can save you a lot of code
axios.interceptors.request.use(config => {
if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
config.headers['Content-Type'] = 'application/json;charset=utf-8';
const accessToken = AuthService.getAccessToken();
if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;
return config;
});
Shubham's answer didn't work for me.
When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization.
The below example is working fine.
var headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
axios.post(Helper.getUserAPI(), data, {"headers" : headers})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
We can pass headers as arguments,
onClickHandler = () => {
const data = new FormData();
for (var x = 0; x < this.state.selectedFile.length; x++) {
data.append("file", this.state.selectedFile[x]);
}
const options = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post("http://localhost:8000/upload", data, options, {
onUploadProgress: (ProgressEvent) => {
this.setState({
loaded: (ProgressEvent.loaded / ProgressEvent.total) * 100,
});
},
})
.then((res) => {
// then print response status
console.log("upload success");
})
.catch((err) => {
// then print response status
console.log("upload fail with error: ", err);
});
};
axios.post can accept 3 arguments that the last argument can accept a config object that you can set header.
Sample code with your question:
var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
headers: {Authorization: token && `Bearer ${ token }`}
})
.then((response) => {
dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
dispatch({type: ERROR_FINDING_USER})
})
If you are using some property from vuejs prototype that can't be read on creation you can also define headers and write i.e.
storePropertyMaxSpeed(){
axios
.post(
"api/property",
{
property_name: "max_speed",
property_amount: this.newPropertyMaxSpeed,
},
{
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + this.$gate.token(),
},
}
)
.then(() => {
//this below peace of code isn't important
Event.$emit("dbPropertyChanged");
$("#addPropertyMaxSpeedModal").modal("hide");
Swal.fire({
position: "center",
type: "success",
title: "Nova brzina unešena u bazu",
showConfirmButton: false,
timer: 1500,
});
})
.catch(() => {
Swal.fire("Neuspješno!", "Nešto je pošlo do đavola", "warning");
});
};
Interceptors
I had the same issue and the reason was that I hadn't returned the response in the interceptor. Javascript thought, rightfully so, that I wanted to return undefined for the promise:
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});