my REST API should send a file to another API and I don't know how to solve it. The only thing i get from the Endpoint API is this curl command:
curl -i -X POST --data-binary #localimg.jpg --header
"X-API-PersonalKey: XXXX-XXXX-XXXX-XXXX" --header "ContentType:application/octet-stream"
http://XXX.XX/..../upload
(btw I have no exp with curl or this functions, so I must learn on the fly.)
I searched and found a tutorial with filesystem Readstream and request POST.
My solution is this (and it dosen't work)
var fs = require('fs');
var url = "http://XXX.XX/..../upload";
console.log(url);
var fdata = fs.createReadStream("c:/xxx/xxx/localimage.jpg");
console.log(fdata);
var options = {
url: url,
headers: {
'X-API-PersonalKey': authToken,
"Content-Type": "application/octet-stream"
},
data: fdata,
body: fdata
};
request.post(options, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log("httpRes =" + httpResponse);
console.log('Upload successful! Server responded with:', body);
});
You need to post multipart/form-data is to use its form feature.
Look at this:
https://stackoverflow.com/a/25345124/4645298
Related
I am trying to hit an API which I got as a curl request. But When I am trying to upload it throwing an error that file is not uploaded. This is my curl request which is working fine.
curl -v -u admin:geoserver -XPUT -H "Content-type: application/zip" --data-binary #/Users/aitplap24/Desktop/WebGIS/uploads/users/61adbbe3ececf2068d6eb862/1638776276622.zip http://localhost:8080/geoserver/rest/workspaces/61adbbe3ececf2068d6eb862/datastores/layer1/61a604021467d3152d5720fa.shp
Here is my NodeJS code for doing the same using requests
const url = process.env.GEOSERVER_URL;
var headers = {
'Content-type': 'application/zip'
};
var dataString = '#/Users/aitplap24/Desktop/WebGIS/uploads/users/61adbbe3ececf2068d6eb862/1638776276622.zip';
var options = {
url: 'http://localhost:8080/geoserver/rest/workspaces/61adbbe3ececf2068d6eb862/datastores/test1/file.shp',
method: 'PUT',
headers: headers,
body: dataString,
formData : {
"file" : fs.createReadStream("/Users/aitplap24/Desktop/WebGIS/uploads/users/61adbbe3ececf2068d6eb862/1638776276622.zip")
},
auth: {
'user': 'admin',
'pass': 'geoserver'
}
};
request(options, (error, response, body) => {
console.log(error, response, body);
});
Error which I am getting
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
I am sure something I am doing wrong with file uploading. Any suggestions is of great help!
Following curl API is successfully deploying .zip file from the local file system into the Azure Function APP.
curl -X POST -u user123:P#ssword --data-binary #"C:\Ddrive\Porject\deploy-zip\wb-uc-code.zip" "https://abc-world.scm.azurewebsites.net/api/zipdeploy"
But I wanna achieve the same with NodeJs: So I converted it as -
function () {
var dataString = "#C:\Ddrive\Workbench\deploy-zip\wb-uc1.zip";
var options = {
url: 'https://abc-world.scm.azurewebsites.net/api/zipdeploy',
method: 'POST',
body: dataString,
auth: {
'user': 'user123',
'pass': 'P#ssword'
}
};
request.post(options, (response, error) => {
if (error) {
console.log("error");
}
else {
console.log(response.body);
}
})
}
while executing am getting error:
------->>>
Most Probably I think am unable to provide file-path appropriately in Options. Can someone help with this?
There are two things you need to pay attention to.
1.You should pass data-binary, you were passing path string in your code.
2.The order of response and error is reversed.
Please refer to the working code as below.
var request=require('request')
var fs = require("fs")
var dataString=fs.createReadStream("D:\\testProject\\NodeJs\\nodejs-docs-hello-world\\test4.zip");
var options = {
url: 'https://tonytestwebnode.scm.azurewebsites.net/api/zipdeploy',
method: 'POST',
body: dataString,
auth: {
'user': 'tonytestweb',
'pass': 'XXXX!'
}
};
request.post(options, (error, response) => {
console.log(response.statusCode);
})
I am trying to fetch the results from all repositories of my organisation under a search category. The results are fetched properly when I use the curl command as shown below
curl -H "Authorization: token ****" -i https://api.github.com/search/code?q=org:<org>+<search_param>
But when I try to run it programmatically in nodejs via the request module it is not returning any results.
My code is as shown below
const request = require("request");
const options = {
url:'https://api.github.com/search/code?q=org:<org>+<search_param>'
headers: {
"Autorization": "token ***",
"User-Agent": "request"
},
json:true
}
console.log(options);
request.get(options, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
The output for the above code is as below
body: {"total_count":0,"incomplete_results":false,"items":[]}
Please let me know what is wrong with the above code or if I am missing anything.
I was able to solve this by using the axios module instead of request module as the request module does not send the Authorization hader. Got a reference from Nodejs request module doesn't send Authorization header.
The updated code which works is as follows
const axios = require("axios");
const options = {
method:"get",
url:'https://api.github.com/search/code?q=org:<org>+<searchtoken>',
headers: {
"Authorization": "token ***",
"User-Agent": "abc"
}
}
console.log(options);
axios(options).then(function ( response) {
console.log('statusCode:', response); // Print the response status code if a response was received
// console.log('body:', body); // Print the HTML for the Google homepage.
}).catch(function (error) {
console.log(error);
});
Thanks #mehta-rohan for the help
I am attempting to set up a webhook to Slack, but am getting an Error message of "Invalid_Payload"
I've looked through Stack, Slack, and Github... but cant' find the answer I seek.
"CustomLink" in there for privacy, actual link is begin used.
CODE:
var request = require('request')
var webhook = "https://hooks.slack.com/services/CUSTOMLINK"
var payload={"text":"This is via an integration from Me - It is a test"}
request.post({url: webhook, payload: payload}, function(err, res){
if(err){console.log(err)}
if(res){console.log(res.body)}
})
ERROR:
invalid_payload
var payload= {"text":"This is via an integration from Me - It is a test"}
payload = JSON.stringify(payload)
I had forgot to stringify the JSON I was creating. Stupid Me.
This worked for me
var payload = {"text":"Message to be sent"}
payload = JSON.stringify(payload);
request.post({url: url, body: payload},function(err,data){
console.log(data.body);
})
My guess is that you are missing the Content-type: application/json header. Then it doesn't recognize the json you are sending as json correctly.
You could try:
var request = require('request')
var webhook = "https://hooks.slack.com/services/CUSTOMLINK"
var payload={"text":"This is via an integration from Me - It is a test"}
var headers = {"Content-type": "application/json"}
request.post({url: webhook, payload: payload, headers: headers}, function(err, res){
if(err){console.log(err)}
if(res){console.log(res.body)}
})
Check the "Send it directly in JSON" here for reference
var request = require('request');
var apiurl = webhookurl;
var payload= {
username:'myusername',
text:'test'
}
payload = JSON.stringify(payload);
request.post(
{
url:apiurl,
form:payload
}, function (err, result, body) {
if(err) {
return err;
} else {
console.log(body);
}
});
Try with postman for sending the post request by using your webhook as URL and under body use raw and use { "text":"hello" } and follow the following image:
or use this curl command:
curl --location --request POST 'https://hooks.slack.com/services/o1GLCDvsanqNDqMHCBQAd7F3' \
--header 'Content-Type: application/json' \
--data-raw '{
"text": "hello"
}'
I'm trying to make an API for saleforeceIQ and their documentation doesn't include Node JS which is what I'm most familiar with. I'm wondering if I could make an API with Node JS from looking at their documentation. Here is their curl documentation get get an account:
DEFINITION
GET https://api.salesforceiq.com/v2/accounts/{accountId}
REQUEST
curl 'https://api.salesforceiq.com/v2/accounts/abcdef1234567890abcdef0b'
-X GET
-u [API Key]:[API Secret]
-H 'Accept: application/json'
RESPONSE
HTTP/1.1 200 OK
{
"id" : "abcdef1234567890abcdef0b",
"modifiedDate" : 1389124003573,
"name" : "Account"
}
Here is what I have come up with so far for converting this to Node JS:
var key = "[KEY]"
var secret = "[SECRET]"
var request = require('request');
var headers = {
'Accept': 'application/json'
};
var options = {
url: 'https://api.salesforceiq.com/v2/accounts/',
headers: headers
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log("body " +body);
}
else{
console.log(error)
}
}
request(options, callback)
My problem is I don't know how to incorporate the key and secret into Node JS
The -u option of curl specify the username and password. So translated for request.js became:
var options = {
// your options
'auth': {
'user': '[KEY]',
'pass': '[SECRET]',
'sendImmediately': true
}
}
You can find more info here: https://github.com/request/request#http-authentication