Friday, 1 September 2017

I am getting “No 'Access-Control-Allow-Origin' header is present” error whenever my client makes an axios request to my backend API.

I recently deployed a backend API using Heroku. It is working.I am now working on my Front-End client that will make use of my Backend API.However, I am getting this error whenever I try to make a request via my client.No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.I added the following middle ware to my server in hopes of resolving this issue.Here is a portion of my index.js file wherein I add the middlewareconst express = require('express'); const passport = require('passport'); const http = require('http'); const morgan = require('morgan'); const LocalStrategy = require('passport-local').Strategy; let path = require('path'); let mongoose = require('mongoose'); let config = require('./config/config'); let bodyParser = require('body-parser'); let recipeRouter = require('./routes/recipeRouter'); let userRouter = require('./routes/userRouter'); const app = express(); // set up DB // mongoose.connect(process.env.MONGODB_URI); mongoose.connect(config.mongoUrl); // mongoose.connect(config.mongoUrl, { useMongoClient: true }); let db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function () { // we're connected! console.log("Connected correctly to server"); }); // Set up App app.use(morgan('combined')); // app.use(bodyParser.json({type: '*/*'})); OLD !!!! // !! NEW !! // app.use(function(req, res, next){ const origin = req.get('origin'); res.header('Access-Control-Allow-Origin', "*"); res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE'); res.header('Access-Control-Allow-Methods', true); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, Pragma, x-auth'); if (req.methods === 'OPTIONS'){ res.sendStatus(204) } else { next(); } }); What am I doing wrong? I followed the answers to the other questions on StackOverflow, but I am still getting this error.

Submitted September 01, 2017 at 08:45PM by T-Dot1992

No comments:

Post a Comment