Yun*_*sha 5 node.js visual-studio-code vscode-extensions
我正在尝试为 Visual Studio Code 构建一个扩展,但我似乎遇到了从扩展内部发出 POST 请求的问题。我创建了一个脚本,该脚本提交一个多部分表单以将文件上传到本地运行的服务器。我已经通过 Postman 测试了 API,它运行良好。我实际上可以从带有 Node 的命令提示符窗口运行脚本,并且它可以很好地提交请求。但是作为 VSCode 扩展(在调试模式)的一部分运行的完全相同的脚本在某些情况下根本无法发出请求,或者它似乎没有正确提交表单。
这是脚本中的代码
//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();
Run Code Online (Sandbox Code Playgroud)
现在使用上面的示例,请求将发送到服务器,但服务器无法理解表单数据,就像我发送了一个空表单一样。
因此,为了测试正在发送的数据,我在 localhost:3000 上设置了一个本地快速回显服务器。同样,从命令行,运行上面的脚本工作正常,我的回显服务器能够读取表单并将其吐回给我。
但是,在 VSCode 扩展调试模式下运行,尝试发布表单时出现此错误:RequestError: Error: write ECONNRESET
那么,我需要做什么特别的事情才能让 VSCode 扩展中的 HTTP 请求正常工作吗?
据我所知,您的代码中存在一些语法问题,请仔细检查文档。
将 request-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...
});
Run Code Online (Sandbox Code Playgroud)
但如果您想将请求作为表单数据发送,请使用此格式
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
}
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4034 次 |
最近记录: |