Axios may ignore default headers - vue.js

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

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));

Vue + axios : has been blocked by CORS policy

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' => ['*'],
...

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 Interceptors just working after page reload

I'm trying to send the Authorization header inside of all requests, when user is logged in my application.
but, whatever i do, it does not work.
Here is my axios instance and interceptor code.
import axios from 'axios'
import storage from '#/services/storageService'
const user = storage.getObject('currentUser')
export const http = axios.create({
baseURL: 'http://localhost/api',
})
http.interceptors.request.use((config) => {
if(user){
console.log(user)
config.headers.Authorization = user.token
}
return config
}, (err) => {
console.log(err)
return Promise.reject(err)
})
in my modules i'm importing the http instance like this
import { http } from '#/http'
export const getItems = () => {
return http.get('items').then( response => response.data)
}
So, clarifying, this code above works, but the header is not present on my request.
To get the interceptor working i need to force a page reload.
Anyone know how can i avoid this?
I solved my problem following #jacky's tip. Now my code runs as following.
import axios from 'axios'
import storage from '#/services/storageService'
export const http = axios.create({
baseURL: 'http://localhost/api',
})
http.interceptors.request.use((config) => {
let user = storage.getObject('currentUser')
if(user){
console.log(user)
config.headers.Authorization = user.token
}
return config
}, (err) => {
console.log(err)
return Promise.reject(err)
})

Angular2 auth token in header request CORS/Preflight issue

I'm trying to request a HTTP GET call to my local REST REST http://demosite.com/mage_auth/api/rest it needs an authorization token to let a user call an endpoint.
So in my request I passed headers.set('Authorization', token) and content-type JSON, however it doesn't seems to be passing the header in the Request's Header when I check the network response.
I've created a httpClient Service to pass the auth token: --
createAuthorizationHeader(headers: Headers) {
var sample3Results = (new OAuthSimple()).sign({
path: 'http://www.demosites.com/mage_auth/',
signatures: {
'consumer_key': key,
'shared_secret': secret,
'access_token': token,
'access_secret': tokensecret
}
});
try {
console.debug('Sample 3', sample3Results);
} catch (e) { };
let headerAuth = sample3Results.header;
headers.set('Authorization', headerAuth);
headers.set('Content-Type', 'application/json; charset=UTF-8' );
}
get(url) {
let headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get(url, {
headers: headers
});
}
My component request look like this: --
this.httClient.get('http://www.demosites.com/mage_auth/api/rest/products')
.map(res => res.json())
.subscribe(data => {
console.log('data: ', data);
})
The REST API is running on WAMP server, so I've also added some CORS values in httpd.conf
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "origin, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
</IfModule>
And I'm still getting this Error.
XMLHttpRequest cannot load http://www.demosites.com/mage_auth/api/rest/products. Response for preflight has invalid HTTP status code 400
Just in case, I also added a proxy.config.json from Angular-cli as thought that'd fix it because the request is coming from localhost:4200. But seems wasn't the case, I'm out of idea why it still giving a preflight error.
Can someone point out what's wrong with this request?
That can be a misconfiguration of the CORS filter server side.
As for me, even if my CORS filter was well configured server side, I still faced the same issue. I used the RequestOptions of Angular for the headers. This is how I soved it within my angular service
Angular 2
header.append("Content-Type", "application/json");
header.append("X-Auth-Token", token);
let options = new RequestOptions({headers: header})
return this.http.get(url, options)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
Angular 4.3
Define an interceptor
import {Injectable} from '#angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '#angular/common/http';
import {Observable} from 'rxjs/Observable';
import {AppService} from '../app.service';
#Injectable()
export class Interceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
setHeaders: {
token: `Bearer token`
}
});
return next.handle(request);
}
}
HttpRequests are immutable objects. So we need to copy them and then modidfy the copy.
Import the interceptor in app.module.ts
...
imports: [
BrowserModule,
HttpClientModule,
...
],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true},
AppService
...
]
Use the interceptor in app.service.ts
import { Injectable } from '#angular/core';
import {Http, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import {HttpClient} from '#angular/common/http';
#Injectable()
export class AppService {
constructor(public http: HttpClient) { }
connectServer() {
return this.http.get('url')
.map(response => response);
}
}