【发布时间】:2016-03-21 13:18:47
【问题描述】:
我正在尝试使用cors 模块通过角度$http 访问节点路由。我试过一个简单的
app.use(cors());
但仍然得到错误。我试过从the cors documentation a whitelist of URLs添加
var corsOptions = {
origin: function(origin, callback){
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
app.get('/someroute/:someparam/', cors(corsOptions), function(req, res, next){
mymodule.getData(req.params.someparam, function(err, data){
if (err){
console.log('error with route', err);
}else{
res.json({result: data});
}
});
});
但我仍然收到错误
XMLHttpRequest 无法加载 localhost:8888/someroute/undefined。跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https、chrome-extension-resource。
我认为使用 cors 模块是为了避免这个问题。我该如何解决?
【问题讨论】:
-
我认为您还需要允许它在服务器端
-
CORS 标头需要在服务器上设置,而不是在客户端上。
-
您到底是如何将 Web 应用程序加载到浏览器中的?您的 URL(如错误消息中所引用的)似乎根本没有与之关联的任何方案,并且错误消息抱怨您没有使用 HTTP。
-
@Pointy 这一切都在我的
server.js文件中,所以当我在终端中使用node server.js启动我的服务器时,它不应该存在于服务器端吗? -
@Quentin App 使用
app.get('/', function(req, res){ res.sendfile('./index.html'); });加载到浏览器中,所以我转到 localhost:8888 然后我看到了索引页面。在该页面上有一个 ng-click 按钮,$http会到达我在问题中显示的路线。
标签: javascript angularjs ajax node.js cors