gpt4 book ai didi

node.js - Express JS - 网络连接丢失

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:21:59 27 4
gpt4 key购买 nike

我正在尝试设置一个将托管 mongodb 数据库的快速 js 服务器。一切都非常标准:我打开了一些路由,它们将从客户端获取数据,然后将其存储在数据库中。

这是我的查询字符串:

let url = "http://xxx.xxx.xx.xxx:3000/update/data="+ JSON.stringify(params);

我注意到,如果 params 不包含很多信息,它就可以正常工作。但是,如果 params 包含大量信息,则客户端会抛出此错误:

Failed to load resource: The network connection was lost.
Http failure response for (unknown url): 0 Unknown Error

(同样的错误在 Safari 和 Chrome 中都会发生。)

例如,如果参数如下:

{
"accountId": "12345678910",
"data": [
1, 2, 3, 4
]
}

那就没问题了。但是,如果 params.data 是一个包含大量信息的巨大数组,而不仅仅是 [1, 2, 3, 4],则会抛出错误。

此外,我的 express 服务器似乎从来没有收到过请求。没有日志;没有什么。我期望发生的只是一个正常的响应和结果,但是看起来客户只是放弃发送大的东西。也许这与将它作为一个大字符串发送有关?

最佳答案

您将数据放在您的 URL 上。但是,URL 的长度有限。

您需要使用 POST 并将您的数据放在 HTTP 请求正文中。

您没有向我们展示您如何使用该 URL,因此很难就更改您的代码提出建议。 Using the http request operation is the way to go .像这样的东西可能有用......

const payload = JSON.stringify(params); 
const url = 'http://xxx.xxx.xx.xxx:3000/update/';

const options = {
method: 'POST', // <--- tell it to POST
headers: {
'Content-Type': 'application/json', // <--- tell it you're posting JSON
'Content-Length': payload.length; // <--- tell it how much data you're posting.
}
};

const req = http.request(url, options, (res) => {
/* handle stuff coming back from request here */
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
let chunks=[];
res.on('data', (chunk) => {
chunks.push(chunk);
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
const resultingData = chunks.join();
console.log('No more data in response.');
});
});

req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});

// write data to request body
req.write(payload);
req.end();

关于node.js - Express JS - 网络连接丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54678878/

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