gpt4 book ai didi

node.js - VSCode 扩展 REST 调用不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 00:04:12 25 4
gpt4 key购买 nike

我正在尝试为 Visual Studio Code 构建一个扩展,我似乎遇到了从扩展内部发出 POST 请求的问题。我创建了一个脚本,该脚本提交一个多部分表单以将文件上传到本地运行的服务器。我已经通过 Postman 测试了 API,它工作正常。我实际上可以使用 Node 从命令提示符窗口运行脚本,它可以很好地提交请求。但是作为 VSCode 扩展的一部分运行的完全相同的脚本(在 Debug模式下)在某些情况下根本无法发出请求,或者它似乎无法正确提交表单。

这是脚本中的代码

//Sync a package to the AEM server
const PACKAGEMGR_PATH = "/crx/packmgr/service.jsp";
const fs = require('fs');
var rp = require('request-promise');
rp.debug = true;
const parseUrl = require('url').parse

class Sync {
syncPackage(packagePath, host, port, username, password) {
var url = parseUrl("http://" + username + ":" + password + "@" + host + ":" + port + PACKAGEMGR_PATH);
var auth = Buffer.from(url.auth).toString('base64');
var cleanURL = "http://" + url.host + url.path;
console.log('Basic ' + auth);
console.log(cleanURL);
return new Promise((resolve, reject) => {
rp({uri: "http://localhost:3000", formData: {
"file": fs.createReadStream(packagePath),
"force": "true",
"install": "true",
"name": "file"
}, method: "POST", headers: {'Authorization': 'Basic ' + auth}}).then((resp) => {
console.log(resp);
}).catch((err) => {
console.error(err);
})
});
}
}

module.exports = new Sync();

在上面的示例中,请求将发送到服务器,但服务器无法理解表单数据,就好像我发送了一个空表单一样。

因此,为了测试正在发送的数据,我在 localhost:3000 上设置了一个本地快速回显服务器。同样,从命令行运行上面的脚本运行良好,我的回显服务器能够读取表单并将其吐回给我。

但是,在 VSCode 扩展 Debug模式下运行时,我在尝试发布表单时遇到此错误:RequestError:错误:写ECONNRESET

那么,为了让 VSCode 扩展中的 HTTP 请求正常工作,我需要做些什么特别的事情吗?

最佳答案

据我所知,您的代码中存在一些语法问题,请仔细检查文档。

将请求 promise 与 json 数据一起使用

var options = {
method: 'POST',
uri: 'http://api.posttestserver.com/post',
body: {
some: 'payload'
},
json: true // Automatically stringifies the body to JSON
};

rp(options)
.then(function (parsedBody) {
// POST succeeded...
})
.catch(function (err) {
// POST failed...
});

但是如果你想发送请求作为表单数据使用这种格式

var options = {
method: 'POST',
uri: 'http://posttestserver.com/post.php',
form: {
// Like <input type="text" name="name">
name: 'Josh'
},
headers: {
/* 'content-type': 'application/x-www-form-urlencoded' */ // Is set automatically
}
};

关于node.js - VSCode 扩展 REST 调用不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934192/

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