在NodeJS中获取页面的HTML源代码

时间:2017-07-29 03:16:24

标签: javascript jquery node.js webpack cors

由于角色限制,我目前正努力在NodeJS中获取网页的HTML源代码。使用JQuery我向页面发出GET请求,期待HTML响应。但是这会引发错误XMLHttpRequest cannot load https://www.reddit.com/. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access。有没有办法绕过使用NodeJS的CORS? (如通过代理)

        $.ajax({
        url: 'https://www.reddit.com/',
        headers: {
            'Content-Type': 'text/html',
            "Access-Control-Allow-Origin": '*'
        },
        type: "GET",
        data: {
        },
        success: function (result) {
            console.log(result);    
        },
        error: function () {
            console.log("error");
        }
    });

我还使用带有以下标题的webpack dev服务器

    headers: {
        "Access-Control-Allow-Origin": '*',
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS"
    }

1 个答案:

答案 0 :(得分:0)

不要在nodejs中使用jquery,你可以使用这个库来满足你的需要:

希望有所帮助