Express启用CORs标头仍然会导致错误

时间:2016-10-11 20:32:25

标签: javascript node.js google-chrome express cors

使用http://enable-cors.org/ for express提供的代码我已添加到我的index.js文件中

  def setMinAndMaxValue(currentCompany: CurrentCompany, matchIterator: Iterator[Regex.Match]): CurrentCompany = {
    var max = 0
    println(s"matchIterator - $matchIterator")
    matchIterator.collect {
      case regex(s: String) => println("found string")
      case regex(IntConv(x)) =>
        println("regex case")
        if (x > max) max = x
    }
    val (minVal, maxVal) = rangesForMaxValue(max)
    val newDetails = currentCompany.details.copy(minSize = Some(minVal), maxSize = Some(maxVal))
    currentCompany.copy(details = newDetails)
  }

object IntConv {
  def unapply(s : String) : Option[Int] = Try {
    Some(s.toInt)
  }.toOption.flatten
}

localhost:3333 / us 正确显示了json,但是从 localhost:3000 (由browsersync提供服务的端口)发出请求失败,错误

  

/*these first five line direct from http://enable-cors.org/.com*/ 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(); }); var PORT = 3333; app.listen(PORT, function(){ console.log('listening on port', PORT); }) request({url: 'http://bl.ocks.org/mbostock/raw/4090846/us.json', json: true}, function(err, data){ app.get('/us', function(req, res, next){ console.log(req) //prints correctly res.json(data.body); }); });

这不再是在express上为localhost启用CORS的正确方法吗?我还尝试将d3.min.js:1XMLHttpRequest cannot load localhost:3333/us. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.方法app.use'*'作为第一个参数传递,但没有运气。

2 个答案:

答案 0 :(得分:1)

进行Ajax调用时,您需要一个包含协议的完全限定的URL。这不是合法网址:

localhost:3333/us

这是你可以在浏览器中输入的东西,浏览器会自动添加一个协议(浏览器会做各种各样的事情,试图将你在URl栏中输入的内容变成一个合法的URL,但那个逻辑确实如此通过Javascript和Ajax发出的请求不会发生。而是将URL更改为:

http://localhost:3333/us

答案 1 :(得分:-2)

我建议只使用npm安装“cors”作为依赖。完成后,只需要并在您想要允许CORS的所有路由之前使用它。

// Dependancies
var cors = require('cors');

// Init express app
var app = express();
app.use(cors());

// Routes now allow cors
app.get('/api/endpoint', controllers.endpoint);