首页 > 解决方案 > 如果我在本地运行 Node.js 服务器,我应该在 http 请求中使用什么作为参数“url”?

问题描述

我正在尝试向我的本地服务器(由 Node.js 运行)发出一个简单的 http 请求。我需要的网址应该是什么样子?

我正在尝试使我的网站以下一种方式运行:单击按钮后,脚本运行。脚本形成 http 请求并将其发送到我的节点服务器,我使用命令行在我的计算机上本地运行。Node 服务器处理 http 请求,从我的 mongodb 数据库中获取数据,并用这些数据响应我的脚本。最后,脚本必须将数据作为网页内容输出。问题是我在浏览器控制台中收到此错误:

'从源'null' 访问'file:///C:/.../serverSide.js' 的 XMLHttpRequest 已被 CORS 策略阻止:跨源请求仅支持协议方案:http、data、chrome、铬扩展,https。

我想这是因为无效的 url,我在我的 http 请求中用作参数。我的所有文件(html、脚本和节点服务器端)都在同一个文件夹中。我已经使用了以下url值:'serverSide.js', 'http://localhost:8080/''localhost:8080'并且它们都导致了上面的错误。那么,我应该用作url什么?

我的脚本:

function textOutput() {

    let xhttp = new XMLHttpRequest();

    xhttp.onreadystatechange = function () {
        if ( this.readyState == 4 && this.status == 200 ) {
            document.getElementById('questionText').innerHTML = 
this.responseText
        }
    };

    xhttp.open('GET', 'serverSide.js', true);
    xhttp.send();
};

这是我处理请求的服务器端的一部分:

...
http.createServer(function (req, res) {
    ukrlitquestions.findOne({id: randomId(1, docsAmount)}, 'text', 
function(err, result) {
        if (err) console.log(err);
        let quesText = result.text;
        res.write(quesText);
        console.log(quesText);
        res.end();
    });
}).listen(8080);
...

标签: javascriptnode.jsajaxhttpmongoose

解决方案


您需要指向正确的域。就像是http://localhost:3000/server-side.js


推荐阅读