GET请求在客户端到服务器给出错误没有'Access-Control-Allow-Origin'

我正在本地主机上运行我的节点/expressionjs应用程序。 我正在向Instagram的api发送'GET'请求,并不断收到此错误:

XMLHttpRequest cannot load https://api.instagram.com/oauth/authorize/?client_id=******&redirect_uri=http://localhost:4000/feed&response_type=code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access. 

我在我的服务器中这样请求:

 app.use(function(req, res, next) { res.header("Access-Control-Allow-Headers: x-requested-with"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); app.get('/',function(req,res){ res.redirect(redirected to feed route); }) app.get('/feed',function(req,response) { var code = req.query.code; var url = "https://api.instagram.com/oauth/access_token"; var options = { url: url, method: "POST", form: { client_id : clientId, client_secret : client_secret, grant_type: 'authorization_code', redirect_uri: redirect_uri, code: code }, json: true } request(options, function(err,res,body){ var instagram_response = body; response.json({access_info:instagram_response}); }) }) 

从我的服务器路由访问“/”数据工作正常。 当我在客户端(在Gallery.html加载时)使用下面的jQuery调用服务器的'/'路线,它给了我错误。 下面是在客户端加载gallery.html时运行的函数。

 $(function(){ $.get("/", function( instagram_reponse, access_token) { access_token = instagram_reponse.access_token; }) }) 

我得到这个错误,因为我的节点服务器在本地主机上运行? 我究竟做错了什么?

您需要在节点上安装CORS软件包..

 $ npm install cors 

var express = require('express'),cors = require('cors'),app = express();

 app.use(cors()); app.get('/products/:id', function(req, res, next){ res.json({msg: 'This is CORS-enabled for all origins!'}); }); app.listen(80, function(){ console.log('CORS-enabled web server listening on port 80'); }); 

configuration选项 来源:configurationAccess-Control-Allow-Origin CORS头。 期望一个string(例如:“ http://example.com ”)。 设置为true以反映请求原点,由req.header('Origin')定义。 设置为false以禁用CORS。 也可以设置一个函数,该函数将请求源作为第一个参数,并且将一个callback函数(期望签名err [object],allow [bool])作为第二个参数。 最后,它也可以是一个正则expression式(/example.com$/)或一组正则expression式和/或string来匹配。

方法:configurationAccess-Control-Allow-Methods CORS头。 期望一个以逗号分隔的string(例如:'GET,PUT,POST')或一个数组(例如:''GET','PUT','POST'])。

allowedHeaders:configurationAccess-Control-Allow-Headers的CORS头。 期望以逗号分隔的string(例如:“Content-Type,Authorization”)或数组(例如:['Content-Type','Authorization'])。 如果未指定,则默认为反映请求的Access-Control-Request-Headers标头中指定的标头。

exposedHeaders:configurationAccess-Control-Expose-Headers的CORS头。 期望以逗号分隔的string(例如:“Content-Range,X-Content-Range”)或数组(例如:['Content-Range','X-Content-Range'])。 如果未指定,则不会显示自定义标头。 凭证:configurationAccess-Control-Allow-Credentials CORS头。 设置为true来传递标题,否则将被忽略。

maxAge:configurationAccess-Control-Allow-Max-Age CORS头。 设置为一个整数来传递标题,否则将被忽略。

preflightContinue:将CORS预检响应传递给下一个处理程序。

有关更多详细信息,请参阅https://www.npmjs.com/package/cors