Slack Webhook - Getting Invalid_Payload - node.js

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"
}'

Related

Fastify get item by title always returning raw JSON as null

I'm just starting with Fastify and ran into an issue where I started creating a get request to get an item by its title, but it keeps giving me a response of null when I try and log the request.body.
My get request:
// Get points by title
fastify.route({
method: 'GET',
url: '/pointz/title',
handler: (request, reply) => {
return request.body
}
})
My get request in postman (as code):
curl --location --request GET 'http://localhost:3000/pointz/title' \
--header 'Content-Type: application/json' \
--data-raw '{
"title": "test"
}'
Screenshot of my input and output in Postman
The expected result would be that the request returns a body that contains the JSON that's being sent, so I can change the code to access request.body.title with a return value of test.
UPDATE:
Found a workaround for now. If I change the GET request to a POST request it works just like it's supposed to. I question however if this is considered good practice.
As discussed in this GitHub Issue GET request validated scheme body?
the body should not be send in GET request, a datailed answer about it
and fastify ignore it by default.
But legacy code does, and if you need to support it, you have to consume the raw request:
const fastify = require('fastify')({ logger: true })
fastify.get('/', async (req) => {
let body = ''
for await (const data of req.raw) {
body += data.toString()
}
return body
})
fastify.listen(3000)
Then your curl command will works as expected.
const got = require('got')
got.get('http://localhost:3000/', {
json: { hello: 'world' },
allowGetBody: true
}).then(res => {
console.log('Returned = ' + res.body)
})

Nodejs, http post json

Here is an example post that I want to do in my Nodejs server to get ClientID and secret.
Request example:
curl --request POST \
--url https://api.opskins.com/IOAuth/CreateClient/v1/ \
--header 'authorization: Basic {{AUTH_HASH}}' \
--data name=TestApp2 \
--data redirect_uri=http://localhost:1234
Response returns JSON structured like this:
{
"status": 1,
"time": 1535408581,
"response": {
"secret": "$nGwYVda##PErKAUpG#kHQ&YA1L)A*X1",
"client": {
"client_id": "ff371b045307",
"name": "TestApp2",
"redirect_uri": "http://localhost:1234",
"time_created": 1535407757,
"has_secret": true
}
}
I am trying with request :
const request = require('request');
var headers = {
'authorization': 'Basic ***my-api-key****'
};
var dataString = 'name=TestApp2&redirect_uri=http://localhost:5000';
var options = {
url: 'https://api.opskins.com/IOAuth/CreateClient/v1/',
method: 'POST',
headers: headers,
body: dataString
};
function callback(error, response, body) {
console.log(body);
}
request(options, callback);
but getting error output like this :
{"status":401,"time":1540115259,"message":"API Key Required"}
I have been trying different codes and middlewares but couldn't make it. Also my test works perfect on Postman. I need help to post that and get my client_id and secret.
I found a way. It was really tricky for me. I needed to use my API Key and also client id.
Bellow codes worked. Thank you very much vitomadio !
I used reqclient from npm.
here is my code
var client = new RequestClient({
baseUrl:"https://api.opskins.com/IOAuth/CreateClient/",
debugRequest:true, debugResponse:true,
auth: {
user:"***My_apikey****",
}
});
var resp = client.post("v1/", {"name": "testApp2", "redirect_uri":"http://localhost:5000/"},{headers: {"authorization":"Basic **my_clientID"}}).then(response => {
// console.log(response);
});
also I am really curies and would like to know how can I do that with request.

nodejs Upload file Using REST

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

I have curl documentation for how to use a site's APIs but would like to use Node JS for the API

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

How do I duplicate this CURL request within nodejs?

I am trying to duplicate the following CURL request within nodejs using request-promise (eventually, I need to use promises so I would prefer this method):
curl -H "Authorization: Token token=[API Key]" -H "Accept: application/vnd.moonclerk+json;version=1" https://api.moonclerk.com/customers
The following code snippet shows my attempt:
var rp = require('request-promise');
var querystring = require('querystring');
//this is what I think is causing me trouble
var bodyHeaders = querystring.stringify({
"Authorization": "Token token=[token taken out in code snippet]",
"Accept": "application/vnd.moonclerk+json;version=1"
});
var options = {
uri: 'https://api.moonclerk.com/customers',
method: 'GET',
body: bodyHeaders
};
var cb = function () {
return function (response) {
console.log("response: ", response);//this should spit out the JSON text I'm looking for
}
}
rp(options).then(cb())
But I am getting Possibly unhandled StatusCodeError: 401 - HTTP Token: Access denied. in the nodejs console as a response. What's the issue here?
PS -- Note that my uri is an HTTPS (i.e., 'https://api.moonclerk.com/customers'); is this what's causing the problem?
You can't pass HTTP headers in the request body, server can't recognize them there. See https://github.com/request/request#custom-http-headers for correct usage of the request library.
var options = {
// ...
headers: {
"Authorization": "Token token=[token taken out in code snippet]",
"Accept": "application/vnd.moonclerk+json;version=1"
}
});

Resources