在 nuxt express 中间件中启用 cors

Geo*_*nov 6 node.js vue.js nuxt.js

我在 src/api/* 中有一个带有 express 中间件的 nuxt 应用程序

我想为这个中间件启用 cors,以便另一个前端应用程序(在不同的域上)可以向它发送请求

由于某种原因,下面的代码没有按预期工作

同样有趣的是,localhost:8000/api/*使用 postman 的请求返回 HTML,而不是我从我的 express 中间件返回的 json 数据。

但是,如果我注释这行代码app.use(cors());(删除 cors 用法),一切都会按预期工作。

这是我的代码

src/api/index.js

const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const mongoose = require('mongoose');
const cors = require('cors');
const config = require('./config');
const syntaxErrorHandler = require('./middlewares/syntaxError')
const api = require('./routes/api');

mongoose.connect(config.database, {
  useCreateIndex: true,
  useNewUrlParser: true,
});

mongoose.connection.on('connected', () => {
    console.log('Mongoose default connection open to ' + config.database)
});

mongoose.connection.on('error', (err) => {
    console.log('Mongoose default connection error: ' + err)
});

const app = express();

app.use(cors());
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(syntaxErrorHandler);

app.use(api);

// export the server middleware
module.exports = {
  path: '/api',
  handler: app
}
Run Code Online (Sandbox Code Playgroud)

nuxt.config.js

const pkg = require('./package')

module.exports = {
  server: {
    port: 8000
  },
  mode: 'universal',

  serverMiddleware: [
    '~/api/index.js'
  ],

  /*
  ** Headers of the page
  */
  head: {
    title: pkg.name,
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: pkg.description }
    ],
    link: [
      ...
    ],
  },

  /*
  ** Customize the progress-bar color
  */
  loading: { color: '#009def' },

  /*
  ** Global CSS
  */
  css: [
    '@/assets/stylus/main.styl',
  ],

  plugins: [
    ...
  ],

  router: {},

  /*
  ** Nuxt.js modules
  */
  modules: [
     ...
  ],


  /*
  ** Build configuration
  */
  build: {
    /*
    ** You can extend webpack config here
    */
  }
}

Run Code Online (Sandbox Code Playgroud)

Met*_*bre 0

我对 cors npm 包也没有运气,所以我使用像这样的普通标头来允许来自所有站点的请求:

const app = express()

// allow all CORS
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  next()
})
Run Code Online (Sandbox Code Playgroud)

这种轻型解决方案的一个优点是您不需要添加另一个包。