npm cors package not working

橙三吉。 提交于 2020-01-15 11:05:28

问题


I'm having trouble accessing my server even with the npm cors package installed.

import Express from 'express';
import compression from 'compression';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';

/**********************

 SERVER CONFIG

 *********************/

import serverConfig from './config';
import auth from './routes/v1/auth.routes'

// Initialize Express
const app = new Express();

// DB Setup
mongoose.connect(serverConfig.mongoUrl, error => {
  if (error) {
    throw new Error('Please make sure Mongodb is installed and running!');
  } else {
    console.log(`MongoDB is running on port ${serverConfig.mongoUrl}`);
  }
});
mongoose.Promise = global.Promise;

/**********************

 MIDDLEWARE

 *********************/

app.use(cors({
    origin: ['http://localhost:8080'],
    credentials: true
  }));
app.use(compression());
// Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
// This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:
/**********
 MULTIPARTY

 - It will not create a temp file for you unless you want it to.
 - Counts bytes and does math to help you figure out the Content-Length of the final part.
 - You can stream uploads to s3 with aws-sdk, for example.
 - Less bugs. This code is simpler, has all deprecated functionality removed, has cleaner tests, and does not try to do anything beyond multipart stream parsing.
 *********/
app.use(bodyParser.json({ limit: '20mb' }));
app.use(bodyParser.urlencoded({ limit: '20mb', extended: false }));
app.use('/api/v1', auth);

/**********************

 START EXPRESS SERVER

 *********************/

app.listen(serverConfig.port, () => {
  console.log(`Server started on port: ${serverConfig.port}`);
});

Router file

import { Router } from 'express';
import * as AuthController from './controllers/auth.controller';

import * as passportConfig from '../../utils/passport.config';
import Passport from 'passport';

// Since we are using tokens, we don't want passport to create a cookie-based session
const requireAuth = Passport.authenticate('jwt', { session: false }); // use after sign in or signed up
const requireSignin = Passport.authenticate('local', { session: false }); // before signin

const router = new Router();

/**********************

 AUTHENTICATION

 *********************/

// Sign Up New User
// Don't need middleware because signup producers token
router.route('/signup').post(AuthController.signup); 
// Sign in Existing User
// Need to provide token after localStrat
router.route('/signin').post(requireSignin, AuthController.signin); 

export default router;


回答1:


You should also define your origin url inside cors function as,

app.use(cors({
    origin: ['http://localhost:8080'],
    credentials: true
}));

Hope this helps.



来源:https://stackoverflow.com/questions/41220873/npm-cors-package-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!