javascript - 如果我在本地运行 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);
...
解决方案
您需要指向正确的域。就像是http://localhost:3000/server-side.js
推荐阅读
- macos - Vim/Terminal 配色方案出现在 SSH 上,但不在本地 Mac 上
- kibana - Kibana 在 CentOS7 Core 中每 14 秒重启一次
- google-apps-script - 在谷歌表格中 - 如何应用 onEdit 触发器以仅在一张表格上的一个单元格上运行?
- python - 如何将多个图像从一个文件夹移动到python中的另一个文件夹?
- css - 内联时如何设置2个输入具有最小宽度?
- javascript - 在javascript中拆分字符串两次
- javascript - ASP.net API 响应,不返回 json
- c# - 未从 asp.net core webapi 在 Application Insights 中打印日志
- r - 按R中具有间隔的列排序
- java - 如何从android应用程序向WHMCS安装发送正确的发布请求?