Psyched
Psyched

Reputation: 11

Cross-Origin Request Blocked even with headers

I am getting this error when trying to do a get request from my vue app. I am running an express Node.js express app that is connected to my local Mysql server. I already have the headers set to allow my Vue app running on localhost:8081 to access the node server but I'm still getting the error. I have CORS installed on node and vue. My teamates are using the same code I am and not getting this but I am still getting the CORS errors(image for errors). Any help would be greatly appreciated. Thanks!

app.js for my node server

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

const cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/courses');

var app = express();

var corsOptions = {
  origin: 'http://localhost:8081',
}

app.use(cors(corsOptions));
app.options('*', cors());

app.get('http://localhost:8081', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var mysql = require("mysql");
app.use(function(req, res, next){
  res.locals.connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'course'
  })
  res.locals.connection.connect();
  next();
});


app.use('/api', indexRouter);
app.use('/api/courses', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});



module.exports = app;

course-services.js for rest requests to my node app

import axios from "axios";

var baseurl = "";
if (process.env.NODE_ENV === "development") {
  baseurl = "http://localhost/api/";
} else {
  baseurl = "/api/";
}

const apiClient = axios.create({
  baseURL: baseurl,
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
    "Access-Control-Allow-Origin" : "*",
    crossDomain: true
  },
  transformRequest: (data, headers) => {
    let token = localStorage.getItem("token");
    let authHeader = "";
    if (token != null && token != "") authHeader = "Bearer " + token;
    headers.common["Authorization"] = authHeader;
    return JSON.stringify(data);
  },
  transformResponse: function(data) {
    data = JSON.parse(data);
    if (!data.success && data.code == "expired-session") {
      localStorage.deleteItem("token");
    }
    return data;
  }
});

export default {
  getCourses() {
    return apiClient.get("courses");
  },
  getCourse(id) {
    return apiClient.get("courses/" + id);
  },
  addCourse(course) {
    return apiClient.post("courses", course);
  },
  updateCourse(courseId, course) {
    return apiClient.put("courses/" + courseId, course);
  },
  deleteCourse(courseId) {
    return apiClient.delete("courses/" + courseId);
  },
};

Upvotes: 0

Views: 953

Answers (2)

cookie s
cookie s

Reputation: 75

I don't know why your setting headers many times if you use cors() module you don't have to set header again

var corsOptions = {
  origin: 'http://localhost:8081',
}

app.use(cors(corsOptions));
app.options('*', cors());

This route is enough and use as middleware for certain routes And at last, only fetch from http://localhost:8081 don't fetch from any random chrome dev console which will violent cors policy as you setting a specific port and domain as localhost:8081 and please check that you using 127.0.0.1:8081 if so it will again throw an error

only use http://localhost:8081 If you use 127.0.0.1 will not work cause the host don't match Hope this will help with your problem

Upvotes: 1

R...
R...

Reputation: 2570

You have a custom header in your request:
"X-Requested-With": "XMLHttpRequest",

Either you need to remove it from request header or you need to support it in your server response header by setting it in 'Access-Control-Allow-Headers' : if you think there might be more custom headers simply set it to *

res.setHeader('Access-Control-Allow-Headers', '*');

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers

Upvotes: 0

Related Questions