[英]VSCode Extension REST calls not working
我正在尝试为 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();
现在使用上面的示例,请求将发送到服务器,但服务器无法理解表单数据,就像我发送了一个空表单一样。
因此,为了测试正在发送的数据,我在 localhost:3000 上设置了一个本地快速回显服务器。 同样,从命令行,运行上面的脚本工作正常,我的回显服务器能够读取表单并将其吐回给我。
但是,在 VSCode 扩展调试模式下运行,尝试发布表单时出现此错误:RequestError: Error: write ECONNRESET
那么,我需要做什么特别的事情才能让 VSCode 扩展中的 HTTP 请求正常工作吗?
据我所知,您的代码中有一些语法问题,请仔细检查文档。
对json
数据使用 request-promise
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
}
};
我遇到了同样的问题,并且能够确认这只是 VSCode 扩展的问题——浏览器和其他请求正常成功。
转到您的快速服务器并将“localhost”添加到此行:
app.listen(PORT, () => {console.log(`Server running on port ${PORT}`)})
像这样:
const express = require('express')
const app = express()
const PORT = 3001
app.listen(PORT, 'localhost', () => {
console.log(`Server running on port ${PORT}`)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.