我的机器上有一个 Rust 服务器在本地主机上运行,端口:4200。我正在尝试使用使用 axios 库的 JavaScript 客户端向该服务器发出请求。
代码运行时出现以下错误:
Error: connect ECONNREFUSED 127.0.0.1:4200 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)
我尝试重写代码以使用获取库。这也会返回连接拒绝错误。
当从 Postman 尝试时,API 可以按要求工作。 Get 调用也可以在浏览器中进行。无法找出从 JavaScript 调用时此调用的连接被拒绝的原因。
我已在 Rust 服务器中启用了 CORS 选项。
fn main() {
let options = rocket_cors::Cors::default();
rocket::ignite()
.mount("/", routes![index, sign, generate])
.attach(options)
.launch();
}
编辑:
从我的机器运行时出现上述错误的客户端代码:
const fetch = require("node-fetch");
var requestOptions = {
method: "GET",
headers: { "Content-Type": "application/json" }
};
fetch("http://localhost:4200/createOffer/1/license", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log("error", error));
在我的机器上运行的浏览器请求: http://localhost:4200/createOffer/1/license
最佳答案
尝试点击http://[::1]而不是http://localhost
我最近尝试在 Rocket 上进行性能测试时遇到了类似的问题。从 v0.4.2 开始,Rocket 似乎无法正确响应 ipv4 和 ipv6 请求。
https://github.com/SergioBenitez/Rocket/issues/541 https://github.com/SergioBenitez/Rocket/issues/209
示例:
const fetch = require("node-fetch");
var requestOptions = {
method: "GET",
headers: { "Content-Type": "application/json" }
};
fetch("http://[::1]:4200/createOffer/1/license", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log("error", error));
关于javascript - JavaScript 应用程序拒绝向 Rust Rocket 服务器发出错误连接请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59539742/