VSCode Extension REST调用不起作用

时间:2018-06-19 17:45:14

标签: node.js visual-studio-code vscode-extensions

我正在尝试为Visual Studio Code构建扩展,但似乎遇到了从扩展内部发出POST请求的问题。我创建了一个脚本,该脚本提交多部分表单以将文件上传到本地运行的服务器。我已经通过Postman测试了API,并且效果很好。我实际上可以从带有Node的Command Prompt窗口中运行该脚本,它可以很好地提交请求。但是,作为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上设置了本地Express echo服务器。再次,从命令行运行上面的脚本可以正常工作,并且我的echo服务器能够读取表格并将其吐回给我。

但是,在VSCode Extension Debug模式下运行时,尝试发布表单时出现此错误: RequestError:错误:写入ECONNRESET

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

2 个答案:

答案 0 :(得分:0)

据我所见,代码中存在语法问题,请仔细检查文档。

要对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
    }
};

答案 1 :(得分:0)

我遇到了同样的问题,并且能够确认这只是 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}`)
})
相关问题