【问题标题】:Can I change super global variables with nodejs like I do with php?我可以像使用 php 一样使用 nodejs 更改超级全局变量吗?
【发布时间】:2015-08-01 22:40:39
【问题描述】:

我可以像使用 php 一样使用 nodejs 更改超级全局变量吗?

如果没有,那么任何人都可以向我指出一个关于如何从客户端进行跨域 http 请求的简单教程吗?你知道,阻止 ajax 到另一个域的 CORS 吗?

【问题讨论】:

    标签: php ajax node.js cors superglobals


    【解决方案1】:

    如果您使用的是 Express 之类的框架,CORS can be done like this

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    
    app.get('/', function(req, res, next) {
      // Handle the get for this route
    });
    
    app.post('/', function(req, res, next) {
     // Handle the post for this route
    });
    

    或者,更简单的是,使用 cors 中间件。

    或者,您也可以使用this gist 作为起点:

    if (req.method === 'OPTIONS') {
          console.log('!OPTIONS');
          var headers = {};
          // IE8 does not allow domains to be specified, just the *
          // headers["Access-Control-Allow-Origin"] = req.headers.origin;
          headers["Access-Control-Allow-Origin"] = "*";
          headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
          headers["Access-Control-Allow-Credentials"] = false;
          headers["Access-Control-Max-Age"] = '86400'; // 24 hours
          headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
          res.writeHead(200, headers);
          res.end();
    } else {
    //...other requests
    }
    

    【讨论】:

    • 跨源请求被阻止:同源策略不允许读取atomedge.org/ajax.php 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。
    • 我相信您也需要在 else 分支中包含 Allow-Origin 以用于您希望启用 CORS 的请求。要点仅显示如何正确处理 OPTIONS 请求。
    • 我在错误的域上添加了 CORS 选项哈哈。我所要做的就是添加一个 Access-Control-Allow-Origin = "*";在php页面中。将您的答案标记为好我会得到一分吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 2017-05-16
    • 2019-10-30
    相关资源
    最近更新 更多