node.js - npm cors 包不工作

标签 node.js express cors

即使安装了 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;

cors error

最佳答案

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

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

希望这有帮助。

关于node.js - npm cors 包不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220873/

相关文章:

javascript - 如何在 electron js 中运行后台服务?

node.js - 不使用框架的纯 Node.js 文件上传(多部分 POST)

javascript - 使用 Jest 测试时,类型错误 : AWS. DynamoDB.DocumentClient 不是构造函数

node.js - async.each 表插入麻烦?

javascript - 请求的资源上不存在 'Access-Control-Allow-Origin' header 。 - Pinterest oauth 实现

javascript - Uber 的 API 在 CORS 预检请求期间返回 404

node.js - npm install -> 无法建立隧道套接字

javascript - 如何访问通过函数传回的 Promise?

node.js - 快速 Node 服务器的 Firefox CORS 失败

typescript - 获取 api 不返回 Location header