axios set headers in config vue js - vue.js

Right now I use axios like this:
import axios from 'axios'
axios.get(apiObjUrl,
{
headers: {
'Content-type': 'application/x-www-form-urlencoded',
}
})
.then(({data}) => {
How do I set global axios header?
(I need to set localization header to use in all my requests)

Use an Axios interceptor: https://github.com/mzabriskie/axios#interceptors
In config you have the request's headers.

Related

NuxtJS - manage several axios instances

I use NuxtJS 2, and I need to have 2 or more axios instances with different configs.
In VueJS / JS classic, I can just create a new instance of axios:
var axiosElasticSearch = axios.create({
baseURL: 'https://elastic.com/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
But in Nuxt, they apply their own config to handle this, because of the SSR layer.
In my Nuxt config, I have this :
axios: {
baseUrl: process.env.API_URL,
browserBaseUrl: process.env.BROWSER_API_URL,
withCredentials: true,
headers: {
common: {
Accept: 'application/json',
Authorization: 'Bearer ' + process.env.API_TOKEN
}
}
},
And then, I can inject it easily.
Is it possible to manage it in Nuxt? I looked at proxy option, but I don't think it's what I want.
nuxt/axios allows creating new Axios instances with $axios.create, which takes the Axios config from nuxt.config.js into account.
For example, you could create a Nuxt plugin that injects a new Axios instance into the root context:
// ~/plugin/api.js
export default function ({ $axios }, inject) {
// Create a custom axios instance
const api = $axios.create({
headers: {
common: {
Accept: 'text/plain, */*'
}
}
})
// Set baseURL to something different
api.setBaseURL('https://my_api.com')
// Inject to context as $api
inject('api', api)
}
And configure your Nuxt app to use it:
// nuxt.config.js
export default {
plugins: ['~/plugins/api.js']
}
Then your component could use the new Axios instance:
// MyComponent.vue
export default {
fetch() {
this.$api.get(...)
},
asyncData({ $api }) {
$api.get(...)
}
}

Axios not sending cookies in the headers, even using withCredentials: true | Backend FastAPI

My axios config
Using postman I get the cookie just fine, so it's an axios problem.
const api = axios.create({
baseURL: 'http://localhost:8000/',
withCredentials: true,
headers: { crossDomain: true, 'Content-Type': 'application/json' },
})
export default boot(({app}) => {
// for use inside Vue files (Options API) through this.$axios and this.$api
app.config.globalProperties.$axios = axios
// ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
// so you won't necessarily have to import axios in each vue file
app.config.globalProperties.$api = api
// ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
// so you can easily perform requests against your app's API
})
export { axios, api }
const response = await api.get(
'',
)
What am I missing here?
You can't send cookie of localhost any other hostname or ip you can send just different subdomain.
You need same site parameter.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#samesite_attribute

GET http://localhost:3000/api/eventNames net::ERR_CONNECTION_REFUSED

I am trying to get axios working with my vue project so I can test the backend of my app. It seems that I am having issues setting up the axios server as I'm getting a connection refused on the baseURL that I have setup. I posted my api.js file that I created under service/api.js. Any information on things to look at to get this resolved would be greatly appreciated.
/src/service/api.js
import axios from 'axios';
export default () => {
const instance = axios.create({
baseURL: 'http://localhost:3000/api',
withCredentials: false,
headers: {
Accept: "application/json",
"Content-Type": "application/jason"
}
});
return instance;
}

Axios may ignore default headers

I'm using axios in my nuxt project.
When I make a request by setting headers config in the request config, the default headers are ignored on node.js.
When I run the following code on node.js
import axios from "axios";
axios.defaults.headers.common["default-header"] = "default-header";
axios.get("https://jsonplaceholder.typicode.com/todos/1", {
headers: { header1: "header1" },
})
.then((response) => {
console.error(response.config);
});
The response config headers is as follows
headers: {
header1: 'header1'
}
The expected response config headers is as follows
headers: {
default-header: "default-header"
header1: "header1"
}
When I run the following code on browser (like Chrome), response config headers is as expected.
Is this a bug in axios?
I created a repository for verification
https://github.com/mimi6612/nuxt-axios-request-config-sample
I think you are missing the axios.create methode.
import axios from 'axios'
const requestHandler = config => {
config.headers = {
'defaultHeader': 'myDefaultHeaderString'
}
config.crossDomain = true
return config
}
const requester = axios.create()
requester.interceptors.request.use(requestHandler)
export requester

How can access $auth.getToken('local') in a service?

I am new in nuxtjs.i am trying to create a service like EventService.js.From EventService.js i want to get data using axios. but i want to set Authorization header.But can't get the access token from $auth.getToken('local'). i don't want to set Authorization header every axios request.Thanks
import axios from 'axios'
const apiClient = axios.create({
baseURL: `example.com`,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
'Authorization': "Bearer " + **$auth.getToken('local')**
}
})
export default {
getEvents() {
return apiClient.get('/events')
}
}
axios interceptors solved my problem
apiClient.interceptors.request.use(
(config) => {config.headers["Authorization"] =cookies.get("auth._token.local")
.replace(/%/g, " ")
return config
},
function(error) {
return Promise.reject(error) })
You can import 'axios' in your main.js (entry file) and add the following:
import axios from 'axios'
axios.defaults.headers.common['Authorization'] = `Bearer ${localstorage.getItem('token')}`;
And when you setup your token for the first time, your can set it up on the localstorage and assign again to the axios defaults headers:
import axios from 'axios'
const token = <AUTH_TOKEN>
// when setting the token
localstorage.setItem('token', token)
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
This will be enough to send the Authorization header in every axios request you make.