【问题标题】:npm cors package not workingnpm cors 包不工作
【发布时间】:2017-05-04 09:41:00
【问题描述】:

即使安装了 npm cors 软件包,我也无法访问我的服务器。

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

路由器文件

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;

【问题讨论】:

    标签: node.js express cors


    【解决方案1】:

    您还应该在 cors 函数中定义您的原始 url,

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

    希望这会有所帮助。

    【讨论】:

    • 您可以发布您尝试访问的 api 的代码吗?
    • 我已经更新了我上面的问题以包含更多的服务器代码:)
    • 您可以尝试使用GET 访问上述api。有用吗?
    • 发现问题。本地主机端口存在冲突。这就是为什么仍然出现 cors 错误的原因。您上面的答案超过了问题中的 cors 错误,因此我将其标记为答案:) 谢谢!
    • 本地主机端口的冲突是什么?我遇到了同样的问题
    猜你喜欢
    • 2014-12-06
    • 2015-12-12
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2017-07-14
    • 2018-06-01
    相关资源
    最近更新 更多