使Node.js中的http.request适用于浏览器

时间:2014-05-27 18:36:03

标签: jquery ajax node.js http cross-browser

我想编写一个适用于Node.jsbrowser的代码库插件。我在Node.js中编写基本代码,然后使用节点模块browserify将其转换为支持浏览器版本。当我在GET中执行代码时,我的所有POSTNode.js请求都能正常工作。如果我写ajax请求,它适用于浏览器。我正在使用http节点模块向远程服务器发出请求。如何在不编写任何单独的ajax请求的情况下使远程服务器请求在浏览器版本中工作?主要思想是保持相同的代码库并使其以两种方式工作。 我有以下用Node.js

编写的示例代码
var http = require('http');

function Test() {
    var self = this;
}

Test.prototype.get_data = function() {
    var fetch = http.request("http://stackoverflow.com/", function(res) {
        var result = ""
        res.on('data', function(chunk) {
            result += chunk;
        });
        res.on('data', function(chunk) {
            console.log("response.................");
            console.log(result);
        });
    });
    fetch.on('error', function(e) {
        console.log("error..........");
        console.log(e);
    });
    fetch.end();
    return 'hello world'
};

API = new Test();

module.exports = API;

现在,当我通过调用Node.js执行API.get_data()中的代码时,它对我来说很好。但是在我使用browserify转换代码然后通过HTMLAPI.get_data()文件调用后,当我在chrome中运行时,我收到以下错误XMLHttpRequest cannot load http://stackoverflow.com/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.。知道如何在不为浏览器编写Node.js的情况下使相同的jsonp ajax代码库工作。 下面提到的是我在Mozilla中运行时的标题。

Response Headers
Cache-Control   public, max-age=21
Content-Encoding    gzip
Content-Length  36325
Content-Type    text/html; charset=utf-8
Date    Tue, 27 May 2014 20:03:47 GMT
Expires Tue, 27 May 2014 20:04:10 GMT
Last-Modified   Tue, 27 May 2014 20:03:10 GMT
Vary    *
X-Frame-Options SAMEORIGIN

Request Headers
Accept  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Cookie  __qca=P0-1262336656-1387719953106; __utma=140029553.331521903.1387719953.1389033371.1389035323.13; __utmz=140029553.1389035323.13.13.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); prov=3d930d0c-1785-4421-b319-33036243183e; _ga=GA1.2.331521903.1387719953
Host    stackoverflow.com
Origin  http://127.0.0.1
Referer http://127.0.0.1/index.html
User-Agent  Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0

2 requests

51.2 KB

2 个答案:

答案 0 :(得分:4)

browserify已经拥有http module for the browser,但您无需做任何特别的事情来获取它。这是浏览器化使用require('http')

的脚本时在浏览器中自动使用的内容

请尝试以解决CORS错误问题:

var fetch = http.request({
  host: "stackoverflow.com",
  port: 80,
  path: "/",
  method: "GET",
  withCredentials: false // this is the important part
}, function(res) {
    var result = ""
    res.on('data', function(chunk) {
        result += chunk;
    });
    res.on('end', function() {
        console.log("response.................");
        console.log(result);
    });
});

答案 1 :(得分:0)

您无法从chrome上的本地主机访问此类网址位置,这被标记为CORS安全风险。您可以尝试以下几种操作:1.将页面上传到托管域,然后可以从www.yourdomain.com(而不是本地主机)尝试。尝试在请求中使用https而不是http。