如何在adonis js中配置cors

how to configure cors in adonis js

如何配置cors使其在开发和生产时采用不同的来源?

这是默认的 cors 配置文件的样子

module.exports = {
  /*
  |--------------------------------------------------------------------------
  | Origin
  |--------------------------------------------------------------------------
  |
  | Set a list of origins to be allowed. The value can be one of the following
  |
  | Boolean: true - Allow current request origin
  | Boolean: false - Disallow all
  | String - Comma separated list of allowed origins
  | Array - An array of allowed origins
  | String: * - A wildcard to allow current request origin
  | Function - Receives the current origin and should return one of the above values.
  |
  */
  origin: false,

  /*
}

您可以简单地检查您的 NODE_ENV Environment variable。然后检查是否设置了这个变量,例如生产或开发。

基于CORS Documentation你可以return一个函数。所以我会检查当前环境,然后 return CORS 属性。在您的 cors.js 中,您会看到类似这样的内容

const Env = use('Env')
...
...
origin: function (currentOrigin) {
  if(Env.get('NODE_ENV​') === 'production' {
    return currentOrigin === 'mywebsite.com'
  } else {
    true
  }
}

如果 NODE_ENV 设置为 production 仅允许来自 "mywebsite.com" 的流量,否则所有流量(用于开发)。