gpt4 book ai didi

javascript - 无法从 HttpListenerRequest 读取 InputStream

转载 作者:行者123 更新时间:2023-12-03 09:48:24 26 4
gpt4 key购买 nike

我一直在创建下载管理器,它从 Chrome 扩展程序接收文件名和下载链接。
在本例中,我决定使用 javascript 后台页面将 XMLHttpRequest 发送到环回,并创建简单的服务器来接收消息,后台页面如下所示。

背景.js

function showMessageBox(info, tab) {
var link = decodeURIComponent(info.linkUrl);
var index = link.search(/[^/\\\?]+\.\w{3,4}(?=([\?&].*$|$))/);
var fileName = link.substring(index);
alert("will download from " + link + " soon\n File name : " + fileName);
SendMessage(fileName,link);
}
function SendMessage(fileName, link) {
var xhr = new XMLHttpRequest();
xhr.open("POST","http://localhost:6230", false);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
var JSONstring = JSON.stringify({ FileName: fileName, DownloadLink: link });
xhr.send(JSONstring);
}

以及服务器部分。

    private void StartReciever()
{
while (true)
{
var fileInfo = GetFileInfo();
Execute.OnUIThread(() => WindowManager.ShowDialog(
new NewDownloadViewModel(WindowManager, EventAggregator, fileInfo, Engine)));
}
}

private FileInfo GetFileInfo()
{
using (var listener = new HttpListener())
{
listener.Prefixes.Add("http://localhost:6230/");
listener.Start();
var requestContext = listener.GetContext();
/*var streamReader = new StreamReader(requestContext.Request.InputStream, requestContext.Request.ContentEncoding);
string jsonString = streamReader.ReadToEnd();*/
var stream = requestContext.Request.InputStream;
byte[] buffer = new byte[10240];
var readbyte = stream.Read(buffer, 0, 102400);
string ss = Encoding.UTF8.GetString(buffer, 0, readbyte);
// deserialize string to object

return new FileInfo();
}
}

我想知道为什么发送消息时流读取总是返回 0。

最佳答案

终于,我找到了我忘记的东西!

根据Same-origin policy ,我无法向非同源服务器发送http请求。
我必须使用Cross-Origin XMLHttpRequest与不同源的服务器进行通信。

为此,我需要 Request cross-origin permissions通过将主机名添加到权限部分。
就我而言,我看起来像这样。

"permissions": [
"contextMenus",
"http://localhost/",
"nativeMessaging"
]

现在,我可以接收字符串并反序列化它。

关于javascript - 无法从 HttpListenerRequest 读取 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30949212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com