且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Express和CORS的问题

更新时间:2023-02-15 18:30:37

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

您必须将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);
});