Vue + axios : has been blocked by CORS policy - vue.js

I have vue app using axios ,first made axios default values :
import axios from 'axios'
const token ='xxxxxxxxx'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
axios.defaults.baseURL = 'http://xxxxxxxxx/api/v1/'
then in a page I call axios :
<script>
export default {
data : function () {
return {
games : []
}
},
created: async function(){
await this.axios('games/this',{withCredentials: true,}).then((res)=> this.games=res.json)
}
}
</script>
I get this error from origin 'http://localhost: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
I tried many solution from posts in this site but don't works

CORS issue should be solved on the backend-side.
If you are using Lumen for backend, please make sure you installed Laravel-Cors
https://github.com/spatie/laravel-cors
Then set allowed_origins to * in the config/cors.php file.
...
'allowed_origins' => ['*'],
...

Related

How to enable delete request for nodejs with cors

I am working on a MERN stack app and when ever I send a delete request to my server using fetch api I get a cors error.
"Access to fetch at 'http://localhost:5000/api/users/delete-user' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
I have tried every solution for the problem here but nothing seems to work for me.
Here is my code
import express from 'express';
import mongoose from 'mongoose'
import cors from 'cors';
import productRoutes from './api/product-api.js';
import orderRoutes from './api/order-api.js';
import eventRoutes from './api/event-api.js';
import tutorRoutes from './api/tutor-api.js';
import assignmentRoutes from './api/assignment-api.js';
import userRoutes from './api/user-api.js';
import accomodationRoutes from './api/accomodation-api.js';
const app = express();
const PORT = process.env.PORT || 5000
// Middleware goes here!!!!
app.use(express.json());
app.use(cors());
// Connecting to database
mongoose.connect('mongodb://localhost:27017/hitstore', (err)=>{
if(err){
console.log("Could not connect to db");
} else {
console.log("Connected to the db");
app.listen(PORT, () => console.log(`http://localhost:${PORT}`))
}
})
// Routes
app.get('/', (req,res)=>{
res.json({message: "Hit store api"})
})
// routes middleware
app.use('/api/products', productRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/assignments', assignmentRoutes);
app.use('/api/tutors', tutorRoutes);
app.use('/api/users', userRoutes);
app.use('/api/accomodations', accomodationRoutes);
Here is the code for my frontend
fetch(`${backendUrl}/api/users/delete-user`, {
method: "DELETE",
headers: {"Content-Type": "application/json", "Authorization": localToken},
body: JSON.stringify(userID),
})
.then(res => res.json())
.then(result => {
console.log(result)
})
.catch((err) => {
console.log("Could not send request\nErr: " + err);
})
The default configuration (which you are using) of Express's CORS middleware allows the DELETE method:
{
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
No problem there. However,
because you're explicitly attaching the Authorization header (the one and only so-called non-wildcard request-header name) to your request , and
because you're specifying application/json as the value of the Content-Type request header,
you need to also explicitly allow those headers:
const corsOptions = {
allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));

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

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

Nuxtjs Axios onRequest() not executed for asnycData request

I have configured axios plugin onRequest helper to set Authorization header on API requests like below
1. export default function({ $axios, redirect, app, store }) {
2. $axios.onRequest(config => {
3. var requestURL = config.url;
4. console.log("Making request to " + requestURL);
5. const token = store.state.user.account.token;
6. if (token) {
7. config.headers.common["Authorization"] = `Bearer ${token}`;
8. console.log("Added authorization header");
9. }
10. });
This onRequest helper get invoked for actions in store. But for asyncData in page component, call reaches till line 2 above but never enters the onRequest function.
import axios from "axios";
asyncData({ params }) {
console.log("params: " + params);
return axios
.get(`http://localhost:8080/user/id/${params.id}`)
.then(res => {
return { userData: res.data };
})
.catch(e => {
error({ statusCode: 404, message: "User not found" });
});
}
As I understand all Axios requests should pass through onRequest helper function. Am I missing something here? How to fix this?
When you import axios from 'axios' you're not using the configuration for the axios instance that you specified initially. Instead, you're using an entirely new axios instance.
The correct way would be to leverage the $axios instance from the Nuxt context.
asyncData(context) {
await context.$axios...
}
You can also use the $axios instance directly. An example is:
asyncData({$axios}) {
await $axios...
}

get data from spotify api using implicit grant flow in vue

im new at vuejs and working with api
i wanna connect to spotify api using implicit grant flow
i redirect user to authorize page and get access token, then i set header using axios instance.
this block of code is in main.js
import axios from 'axios'
export const base = axios.create({
baseURL: 'https://api.spotify.com/v1',
header: {
'Authorization' : 'Bearer ' + store.state.accessToken,
}
});
Vue.prototype.$http = base;
and this one is in one of my components that i try to get data from api
mounted() {
this.$http.get('/artists/1vCWHaC5f2uS3yhpwWbIA6')
.then(data => this.albums = data)
.catch(e => this.error = e)
}
but the server responds with 401 error and this message:
Error: Request failed with status code 401
so what do you think?