节点快速服务器,CORS API限制,包括我的开发机器的hosts文件中的条目

时间:2015-03-30 19:33:58

标签: api express cors

我正在尝试使用具有API CORS策略的API,该策略不支持来自任何域的浏览器请求。为了允许客户端JavaScript代码访问API,在开发我的应用程序时,我被建议我从' *。thisCompany.com'提供我的webapp。域。 建议在我的开发机器的hosts文件中包含一个条目,如下所示,我已经完成了:

$ echo '127.0.0.1 localhost.thisCompany.com' >> /etc/hosts

运行sudo nano /private/etc/hosts时执行此命令  这是我看到的屏幕。

Host Database

localhost is used to configure the loopback interface
when the system is booting.  Do not change this entry.
127.0.0.1       localhost
127.0.0.1       localhost.thisCompany.com

然后我被告知我应该可以在http://localhost.thisCompany.com访问我的webapp。

我使用node express作为我的服务器,我的server.js文件中的代码看起来像这样

var express = require('express');
var server = express();
var path = require('path');

var port = process.env.PORT || 'thisCompany.com';

server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));

  server.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/views/index.html'));
  });

  server.listen(port, function() {
    console.log("Node app is running at localhost:" + port)
  });

有人可以建议我应该遵循哪些步骤来调用此API并绕过API CORS策略吗?

我在这里阅读了其他各种帖子,还有其他在线文章,但我找不到解决方案。真的希望有人可以提供帮助。

谢谢,保罗

1 个答案:

答案 0 :(得分:0)

我误解了在修改本地计算机上的hosts文件后,我应该如何在计算机上本地查看页面。我不需要在我的快递服务器上添加任何东西。快速服务器代码保持如下:

var express = require('express');
var server = express();
var path = require('path');

var port = process.env.PORT || 3000;

server.use(express.static(__dirname + '/public'));
server.use('/bower_components', express.static(__dirname + '/bower_components'));

  server.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/views/index.html'));
  });

  server.listen(port, function() {
    console.log("Node app is running at localhost:" + port)
  });

将原始帖子中提到的行添加到本地计算机上的hosts文件后,我需要启动服务器并按照此链接访问该页面。

http://localhost.thisCompany.com:3000/

虽然这是一个非常小众的问题,但我希望这篇文章可以帮助将来的某些人。