how to get 201 status code in web services in node js - json

How can i return the result of post method in api and also 201 status code? In this code the status code is 200 how can i change it to 201?
var request = require('request');
request({
method: 'POST',
url: 'URLPATH',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic Key'
},
body: {
"id":"1","message":"I am Good Developer."
}
}, function (error, response, body) {
console.log('Status:', response.statusCode); //get 201 status but received 200
console.log('Headers:', JSON.stringify(response.headers));
console.log('Response:', body);
});

Here you are calling a web service, is the web service that respond with 200 and not 201.
You need to change the web service code, no the client code.

Related

Error while calling freshchat APIs from google apps script

I am trying to call FreshChat API from google apps script. GET request of outbound-messages is working fine but POST request is failing with error
Exception: Request failed for http://api.in.freshchat.com returned code 400. Truncated server response: {"success":false,"errorCode":0,"errorMessage":"HTTP 405 Method Not Allowed","errorData":null,"errorName":null} (use muteHttpExceptions option to examine full response)
Below are the details of request
function myFunctiontest() {
var url = "http://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = {
'Authorization': 'Bearer XXXXXX',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headersPOST,
'payload': JSON.stringify(bodyPayload),
'muteHttpExceptions':true
};
var response = UrlFetchApp.fetch(url, options);
console.log(response.getAllHeaders());
Logger.log(JSON.parse(response.getContentText()));
}
Same headers are working for GET request. Also same post request is working from POSTMAN.
Freshchat support helped for solving the issue.
There are two major changes
use https instead of http
Added contentType inside headers.
function myFunctiontest() {
var url = "https://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = 'Bearer XXXXXX';
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+ XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
method: 'POST',
//content-type: 'application/json',
headers: { Authorization: headersPOST, 'content-type': 'application/json'},
payload: JSON.stringify(bodyPayload),
muteHttpExceptions:true
};
var response = UrlFetchApp.fetch(url, options);
var text = response.getResponseCode();
}

Requesting access token to Zoom API via Oauth - error 'missing grant type'

I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});

post request in Axios with 400 or 401 - bearer token

I'm trying to post data using axios.
handleAddClickAxios = (token, title, text, category, creationDate) => {
const api = "http://localhost:3000/tasks/";
console.log("login clicked");
let data = JSON.stringify({
title: title,
text: text,
category: category,
creationDate: creationDate,
done: false
});
console.log(data);
axios.post(api, data, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
}
});
};
Now I have 400 error, in some options I got Unauthorized error. I tried many times, but i failed.
Console:
Apptask -
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZGNmZjFhMjQzZWUwNTJmNmNkMjAzYzgiLCJpYXQiOjE1NzQ1ODQzMDl9.P9cKtljoFXbCo6X540tQ27d_jeouOwwRJ6HKhpsy-PY
asdad
App.js:100 login clicked
App.js:108
{"title":"asdad","text":"aaaaaaaaaa","category":"","creationDate":"2019-10-0,
9:31","done":false} :3000/tasks/:1 POST http://localhost:3000/tasks/
400 (Bad Request)
Request details in devtools:
You need to send data without JSON.stringify like this:
let data = {
title,
text,
category,
creationDate,
done: false
};
Also your creationData is not valid, it must be in this format:
"2019-11-24T09:06:29.271Z"

"Problems parsing JSON" while sending a http request to a graphql api

I'm trying to send a http request to Githubs graphql api(v4). My guess is that the format of my query is wrong. The code below is used to send a POST request to the api.
app.get('/fetch-data', function(req, res, next) {
const access_token = settings.dev.TOKEN;
const query = {query: { viewer: { 'login': 'muckbuck' } }};
const options = {
uri: 'https://api.github.com/graphql',
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': "Bearer " + access_token,
'User-Agent': 'request',
'contentType': "application/graphql",
},
data: query
};
function callback(error, response, body) {
console.log(response.body)
if (!error && response.statusCode == 200) {
console.log(body);
console.log('lol');
}
}
request(options, callback);
});
The error message that I get:
{"message":"Problems parsing JSON","documentation_url":"https://developer.github.com/v3"}
I believe your GraphQL is malformed in that the query key is supposed to contain a string, not a complex structure. See also this example from the GitHub API documentation.
You may also want to set Content-Type to application/json as is recommended by the GraphQL introduction. application/graphql does not seem to be a registered media type and appears to alter the behaviour of GraphQL.

Connecting to HTTPS web services API with node.js v4.2.6?

I'm looking at connecting to an https web api, I've obtained my token, and my username by receiving an email about it, and there isn't really any sample code to connect to the webservice using node; however there are examples for Java and C#, and based on those this is what I came up with...
/* WEB API: https://www.careeronestop.org/Developers/WebAPI/technical-information.aspx?frd=true */
// UserID: ...
// Token Key: ...==
// Your agreement will expire three years from today on 12/8/2019 and all Web API services will be discontinued,
// unless you renew.
var https = require('https');
var username = '...';
var tokenKey = "...==";
var options = {
host: 'api.careeronestop.org',
port: 443,
path: '/v1/jobsearch/' + username + '/Computer%20Programmer/15904/200/2',
method: 'GET',
headers: {
'Content-Type' : 'application/json',
'Authorization' : '' + new Buffer(tokenKey.toString('base64'))
}
};
var req = https.request(options, function(res) {
console.log(res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
Unfortunately however, it returns a 401 Unauthorized, so is there anything that needs added to this to get it working? Some headers maybe?
I used this form to submit a request and then looked in the Chrome debugger network tab to see exactly what request was sent.
The authorization header is supposed to look like this:
Authorization: Bearer 901287340912874309123784
You also want this:
Accept: application/json
So, assuming tokenKey is already a string since it appears to have been sent to you in an email, you can change your code to this:
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + tokenKey
}