How can I prevent CORS issue with vue axios?
Following is the code for making requests with the backend using vue and axios.
axios.config.js
/// here I'm creating a vue axios instance.
import axios from "axios";
export default axios.create({
baseURL: "https://example.com/api/v1/",
headers: {
Accept: "application/json",
Authorization: "TOKEN 3413413dfdsfsafd3rr41",
},
});
and inside the vue.config.js
I've proxied the request.
module.exports = {
devServer: {
proxy: {
"/api/*": {
target: "http://localhost:8081",
secure: false,
changeOrigin: true,
},
},
},
};
and inside my vuex store I'm calling an action:
import axios from 'axios.config'
actions: {
getData({ commit }) {
axios
.get(`products/grocery`)
.then((res) => {
console.log("res :", res);
commit("SET_DATA", res.data);
})
.catch((e) => {
console.log("e :", e);
commit("SET_ERROR", e);
});
},
}
But when I look at the request in the console, I can see that it is sending request to the original url https://example.com/api/v1/ rather than appending the dev server line this: http://localhost:8081/api/v1/
Not sure why the proxying is not working!
External URLs doesn't get proxied. Change the base URL in axios to /api/v1/
export default axios.create({
baseURL: "/api/v1/",
headers: {
Accept: "application/json",
Authorization: "TOKEN 3413413dfdsfsafd3rr41",
},
});
Nuxt provides a proxy option which you can use to avoid cors errors,
Nuxt Documentation
You can refer this for more information and available options #nuxt/proxy
Related
I am creating a simple application with Vue, and I call an endpoint with axios
axios.post(url, {
email: this.email,
})
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
I get the error
from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The problem is not at the server level, I have done tests from Postman or directly with CURL and it does not generate an error.
Solution:
Thanks to Shrinivas Bendkhale's comments. I managed to solve the problem.
At first it did not work, so it was necessary to add the "logLevel" and "pathRewrite" options to the proxy.
logLevel: It allows to see in the terminal how the proxy is working
pathRewrite: Add the rest of the path to the proxy
// vue.config.js
module.exports = {
devServer: {
proxy: {
'^/rp': {
target: process.env.API_OLD_SERVER,
secure: false,
logLevel: 'debug',
pathRewrite: {
'^/rp': '/'
}
},
},
},
}
So my call was as follows
axios.post('/rp/full-path', {
usermail: this.email,
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
Inside vue.config.js file add following lines:
// vue.config.js
module.exports = {
// options...
devServer: {
proxy: 'https://mywebsite/',
}
}
I've been trying to get this to work for two days now. I'm a brand new user to Nuxt (although I've used Vue for a few years now), so I'm just trying to wrap my brain around how this all works.
In my Nuxt project I have the Axios module installed:
nuxt.config.js
export default {
plugins: [
...
'~/plugins/axios',
],
axios: {
baseURL: 'https://my-url.com/wp-json/wp-v2',
https: true,
},
}
plugins/axios.js
export default ({ $axios, env }) => {
$axios.onRequest(config => {
$axios.setToken(env.WP_API_KEY, 'Bearer');
});
}
And in my page, I'm trying to use the asyncData function to pull data from my WordPress API, as such:
export default {
async asyncData(context) {
const data = await context.$axios.$get('/media');
console.log(data);
return { data };
}
}
I keep receiving a 401 Not Authorized error however, essentially stating that my Authorization: Bearer <token> isn't being passed through. Using Postman however, I can verify that this endpoint does indeed work and returns all of the JSON I need, so the problem must lie in the way I have the axios global header set up.
It's been tough finding any real example on how to set a global header using the Nuxt/Axios module. I see in the docs how to use setToken, however it doesn't exactly show where to place that.
What do I have set up wrong, and how do I fix it?
Pretty typical that I get it working 15 minutes after I post a question.
Setting the header like this instead seems to work. I'm not sure why the setToken method didn't want to work.
export default ({ $axios, env }) => {
$axios.onRequest(config => {
config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;
});
}
If you are using Nuxt auth module, Here is how I have achived.
// nuxt.config.js
modules: [
'#nuxtjs/auth',
'#nuxtjs/axios',
],
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/auth/login', method: 'post', propertyName: 'accessToken' },
logout: false,
user: { url: '/auth/me', method: 'get', propertyName: false }
},
}
},
redirect: {
login: '/auth/signin',
logout: '/auth/signin',
callback: false,
home: false,
},
cookie: false,
token: {
prefix: 'token',
},
plugins: ['~/plugins/auth.js'],
},
// plugins/axios.js
export default function ({ $axios, $auth, redirect, store }) {
$axios.onRequest((config) => {
config.headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': store.state.auth.tokenlocal, // refers to nuxt.config.js->auth.token
}
})
$axios.onError((error) => {
if (error.response.status === 500) {
redirect('/error')
}
})
}
// store/index.js
export const getters = {
authenticated(state) {
return state.loggedIn;
},
user(state) {
return state.user;
}
};
export const state = () => ({
busy: false,
loggedIn: false,
strategy: "local",
user: false,
});
If you need to customize axios by registering interceptors and changing global config, you have to create a nuxt plugin.
export default ({ $axios, env }) => {
$axios.onRequest(config => {
config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;
});
}
Adding axios interceptors
when I ty yarn dev In server rendering Proxy is working fine. fetching data from API site api.server.com/api
But after yarn generate axios request is calling self server
current.example.com/api.
Why it is not working in dist html?
Is Proxy working only in server side? Please, help.
I have NuxtJS config:
/*
** Nuxt.js modules
*/
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
proxy: true // Can be also an object with default options
},
proxy: {
'/api/': {
target: 'http://api.server.com/api',
pathRewrite: {'^/api/': ''}
},
changeOrigin: true
},
plugins axios.js
import axios from 'axios'
export default axios.create({
baseURL: '/api/',
responseType: 'json'
})
here I called that API like below index.vue
<script>
import axios from '~/plugins/axios'
export default {
mounted() {
this.loaded();
},
methods: {
loaded(){
const location = axios.get('/contact/contact_session.php').then((response) => {
console.log(response);
}).catch((err) => {
});
},
}
}
</script>
The proxy.js module only works in the development environment, in the production environment you must configure your web-server, preferably nginx, the proxy that takes your requests for example from the path "/ api / ..." and redirects it to the server you need.
I know about Axios, but I am trying to do this with Vue Resource.
Everything is working fine but is not sending the headers.
No matter what I do, it won't send the headers.
However, when I execute the query and resend it with Firefox console (after adding the auth header) it does work.
But when executing directly from Vue it does not send the header.
When I try to do the exact same thing in Postman, it does work :)
Question: Does anyone know how to solve this?
this.$http.get('https://myapi.com/v1/whatever/option', {
params: {
},
headers: {
'Authorization' : 'Bearer Cd34dfhnc4jn-39q84cq9-pwncpqw349fn83q47903qpnf98nghwehj5UiDXyC:$2y$1gerg34cqw4yas4yqOHAyLk4wy2OkDvxH6HOs.CgocO2TE9Te'
}
}).then(response => {
//console.log(response);
}, response => {
console.log('error:');
console.log(response.headers.get('Authorization'));
console.log(response);
})
P.S. I just tried Axios, and the same problem here... when I check my request, my added headers are NOT there!?
Download my FF Console screenshot
In my Vue file I have a #click event:
this.$http.get('https://boinu.nl/v1/synonyms/autos', {
// params: {
//
// },
// headers: {
// 'Authorization' : 'Bearer CdcmXCj0pdaM7UH6zpWVRSyncWJHhShHPKzvj4wWxNaxIn54LGQMaVU7ihUiDXyC:$2y$10$26IZut5mWqtECbhVIFnSqOHAyLk4wy2OkDvxH6HOs.CgocO2TE9Te'
// }
}).then(response => {
//console.log(response);
}, response => {
console.log('error:');
console.log(response);
})
and in my main.js I have:
import Vue from 'vue'
import App from './App.vue'
import VueResource from 'vue-resource'
Vue.use(VueResource);
new Vue({
el: '#app',
render: h => h(App)
});
I am writing a nuxt app that authenticates with a backend. I have a http plugin that intercepts all http requests. I need to add an auth token to all requests, the token is in the store. What I want to know is, how do I access the store from the plugin?
import axios from 'axios';
var api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/'
});
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': 'Bearer' + **how do access store?**
}
return config;
}, function (error) {
return Promise.reject(error);
});
export default api;
Thanks
You can try to use app store from context in plugin.
Your plugin need some changes:
import axios from 'axios';
var api = axios.create({
baseURL: 'http://127.0.0.1:8000/api/'
});
export default (context, inject) => {
api.interceptors.request.use(function (config) {
config.headers = {
'Authorization': 'Bearer' + context.app.$store.state.your_path_to_token
}
return config;
}, function (error) {
return Promise.reject(error);
});
return api;
}
One more way it's create store/index.js file and import them into plugin.