I'm trying to build an extension for Visual Studio Code and I seem to be running into issues making a POST request from inside the extension. I've created a script that submits a multipart-form to upload a file to a local running server. I've tested the API via Postman and it works fine. I can actually run the script from a Command Prompt window with Node and it submits the request fine. But that exact same script running as part of a VSCode extension (In Debug mode) either cannot make the request at all in some cases, or it doesn't seem to properly submit the form.
Here is the code in the script
//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();
Now with the example above, the request will make it to the server, but the server can't comprehend the form data and acts as if I sent an empty form.
So to test what data was being sent, I set up a local express echo server on localhost:3000. Again, from command line, running the script above worked fine and my echo server was able to read the form and spit it back to me.
However, running in VSCode Extension Debug mode, I get this error when trying to post the form: RequestError: Error: write ECONNRESET
So, is there something special I have to do to get HTTP requests working properly from a VSCode Extension?
From what I can see you have some syntax issue in the code, double check the documentation.
To use request-promise with json
data
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...
});
But if you want to send the request as form data use this format
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
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With