Express和CORS的问题 [英] Problems with express and CORS

查看:47
本文介绍了Express和CORS的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行带有express的nodejs脚本.我已经阅读了文档,但是我仍然无法发出CROS请求.我正在运行一个Web服务器,以显示其工作方式: http://a56f1bae.ngrok.io/

我真的不知道为什么它不起作用,它几乎与文档中的一样.

这是我的脚本,如果有帮助的话:

  var express = require('express');var app = express();app.use(function(req,res,next){res.header('Access-Control-Allow-Origin',"*");res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');res.header('Access-Control-Allow-Headers','Content-Type');下一个();})app.get('*',函数(req,res){res.send(html);});app.listen(3000,function(){console.log('服务器在端口3000上运行');});var html =`< html>< head>< script>var url ='https://suggestqueries.google.com/complete/search?output=firefox&hl=zh-CN&q=test';var request = new XMLHttpRequest();if('withCredentials'in request){//Firefox 3.5和Safari 4尝试{request.open('GET',url,false);request.send();document.write('做得很好!');}抓(err){document.write(err)}}否则,如果(XDomainRequest){//IE8尝试{var xdr = new XDomainRequest();xdr.open('get',url);xdr.send();document.write('做得很好!');}抓(err){document.write(err)}//处理XDR响应-此处未显示:-)}</script></head></html>`; 

非常感谢您,如果我的问题很明显,对不起.

解决方案

我认为您有一个概念性问题.

您必须将cors标头设置为SERVER而不是CLIENT.
您要从 localhost:3000 访问 suggestqueries.google.com .这意味着在这种情况下,服务器是google.com或我想 google API .这意味着您需要在google API中在那里设置cors.

如果假设您有一个在 localhost:someport 中运行的应用程序并访问了可能用作api服务的 localhost:3000 ,那么您需要将cors添加到Express中应用程序.因为那样的话它将是您的服务器.

查看以下内容: https://developers.google.com/api-client-library/javascript/features/cors

注意:出于开发目的,您可以在chrome中禁用相同的原始策略.请参阅此处以了解操作方法:在Chrome中禁用同一来源策略

修改:一种解决方法
由于Google建议的文档很少,因此您可以使用 jsonp 来解决cors问题.检查:使用JsonP的JavaScript XMLHttpRequest

代替使用 XMLHttpRequest 尝试使用由@paul创建的 jsonp 函数

  function jsonp(url,callback){var callbackName ='jsonp_callback_'+ Math.round(100000 * Math.random());window [callbackName] = function(data){删除窗口[callbackName];document.body.removeChild(script);回调(数据);};var script = document.createElement('script');script.src = url +(url.indexOf('?')> = 0?'&':'?')+'callback ='+ callbackName;document.body.appendChild(script);}jsonp('http://www.helloword.com',function(data){警报(数据);}); 

I am running a nodejs script with express. I have read the documentation but I can't make CROS requests still. I am running a web server to show how it is not working: http://a56f1bae.ngrok.io/

I really do not know why it is not working, it is almost exactly as it is in the documentation.

Here is my script if that helps:

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

app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
})

app.get('*', function (req, res) {
  res.send(html);
});

app.listen(3000, function () {
  console.log('Server running on port 3000');
});



var html = `
<html>
<head>
<script>
var url = 'https://suggestqueries.google.com/complete/search?output=firefox&hl=en&q=test';
var request = new XMLHttpRequest();
  if('withCredentials' in request) {
     // Firefox 3.5 and Safari 4
     try{
       request.open('GET', url, false);
       request.send();
       document.write('It is doing fine!');
     } catch (err){
       document.write(err)
     }
  } else if (XDomainRequest) {
     // IE8
     try{
       var xdr = new XDomainRequest();
       xdr.open('get', url);
       xdr.send();
       document.write('It is doing fine!');
     } catch (err){
       document.write(err)
     }
     // handle XDR responses -- not shown here :-)
  }
</script>
</head>
</html>
`;

Thank you so much and sorry if my question is obviously.

解决方案

I think you have a conceptual problem.

You have to set cors header to the SERVER not the CLIENT.
You want to access suggestqueries.google.com from localhost:3000. That means in this case the server is Server is google.com or I guess google API. That means you need to set the cors there, in the google api.

If let's say you had an app running in localhost:someport and access localhost:3000 which may serve as api service, then you needed to add cors to your Express app. Because then it would have been your SERVER.

Check this out: https://developers.google.com/api-client-library/javascript/features/cors

Note: For development purpose you can disable same origin policy in chrome. refer here on how to do that: Disable same origin policy in Chrome

Edit: A workaround
As there are very little docs for google suggest, You can use jsonp to overcome the cors issue. check: JavaScript XMLHttpRequest using JsonP

Instead using XMLHttpRequest try using the jsonp function created by @paul

function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
}

jsonp('http://www.helloword.com', function(data) {
   alert(data);
});

这篇关于Express和CORS的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆