How to pass data with request module(POST method) on Node.JS? - javascript

I am following the following steps but getting an error. I think it is not passing the body. However get method was working fine with this steps.
var request = require("request");
var should = require("should");
var expect = require("chai").expect;
var baseUrl = "https://na73.salesforce.com/services";
const config = require("../../../lib/config");
const url = require("../../data/url");
describe('Get Call Record Resource list', function() {
this.timeout(config.timeOut);
it('Verify in Dialer Config api, able to get Dialer Config list', function(done) {
request.post({
headers: {
Authorization: `Bearer ${config.token}`
},
body:{
"callId": {
"callConnectService": "RING_CENTRAL",
"serviceCallId": "1564283263244352",
"externalId": "1564283263244352"
},
"appointmentId": "a181I000001IMOlQAO",
"entityId": "0031I00000MxBw8QAF",
"phoneNumberCalled": "+13175221101"
},
url: baseUrl + `${url.CallRecordResource}`
},
function(error, response, body) {
var bodyObj = JSON.parse(body);
expect(response.statusCode).to.equal(200);
expect(response.body).should.exists;
should.not.exist(error);
expect(response.body).to.not.be.undefined;
done();
});
});
});

Related

How to convert code from node.js to JavaScript

I need to rewrite an Api call. The original call is write in Node.js and i'm trying to rewrite the call in Javascript.
Node.js code:
const http = require("https");
const options = {
"method": "POST",
"hostname": "test.com",
"port": null,
"path": "/path",
"headers": {
"Authorization": "Token token-value"
}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(JSON.stringify({
data: {
'Id': 'id value'
},
responsive: false
}));
req.end();
I'm trying in this way:
const url='https://test.com/path'
const bodyContent = {
data: {
'Id': 'id value'
},
responsive: false
};
const options = {
"method":"POST",
"port":null,
"headers": {
"Authorization":"Token token-value"
},
body: JSON.stringify(bodyContent)
}
const res = await fetch(url, options)
I expected a positive response but the response keep saying "Missing value of required parameter 'Id'"

send response from nodejs express to angular app

I am calling an api of sending OTP from my nodejs app. I need to send the response of that OTP Api to the angular app.
my api service on angular look like this:
sendOtp(params): Observable<any> {
return this.apiService.post("/user/send-otp", params)
}
my router on express app look like this
this.router.post("/user/send-otp", userController.sendOtpMessage);
and the code inside userController look like this.
static sendOtpMessage(req, res ,next) {
const phone = req.body.phone;
var http = require("https");
var options = {
"method": "GET",
"hostname": "api.msg91.com",
"port": null,
"path": `/api/v5/otp?mobile=${phone}`,
"headers": {
"content-type": "application/json"
}
};
var callOtpApi = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// I need to send this data in response to my angular app ==>> body.toString()
});
});
callOtpApi.write();
callOtpApi.end();
}
OTP Api ref document: https://docs.msg91.com/p/tf9GTextN/e/B1NUt3C8MY/MSG91
It seems that the code above is missing the res.send() to return the data from server. Could you please try with this?
static sendOtpMessage(req, res ,next) {
const serverRes = res;
// Rest of your code
...
var callOtpApi = http.request(options, function (res) {
// Rest of your code
...
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
// Return data to client
serverRes.send(body.toString());
});
// Rest of your code
...
});
}
You can call the msg91 api using axios
const axios = require('axios');
async function sendOtpTOUser(phone) {
const template = "template _id";
const apiKey = "api_key";
const sendotp = "https://api.msg91.com/api/v5/otp?template_id="+template+"&mobile="+phone+"&authkey="+apiKey;
let request_options1 = {
method: 'get',
url: sendotp
};
let otpResponse = await axios(request_options1);
console.log(otpResponse.data)
return otpResponse.data;
}
it will return the object as
{ request_id: '3166686e7867313634383535', type: 'success' }

Create new product by calliing shopify api

I am trying to create a new product by calling the shopify product api (/admin/api/2020-01/products.json). I am trying to achieve this using the "https" module. Below is the sample code
const url1 = 'https://{api_token}#tuscstore.myshopify.com/admin/api/2020-01/products.json';
var obj = {
"product":[
{
"title": "Saturn",
"body_html": "<p>The epitome of elegance</p>",
"vendor": "Soltions inc",
"product_type": "Planets",
"handle": "saturn",
"tags": "",
"images": [
{
"src": "https://solarsystem.nasa.gov/system/stellar_items/image_files/38_saturn_1600x900.jpg"
}
]
}
]
};
const https = require('https');
var data = JSON.stringify(obj)
const options = new URL(url1);
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
/* res.on('data', (d) => {
process.stdout.write(d);
}); */
});
req.on('error', (e) => {
console.error(e);
});
req.write(data);
req.end();
const Index = () => (
<div>
<p>Sample app using React and Next.js</p>
</div>
);
export default Index;
I am facing 2 problems,
when I do "process.stdout.write(d)", I receive cannot readproperty "write" undefined.
If I comment it out as I have done in
the code above, I don't get the error.
In either case I get the statuscode as 200, and not 201 which is what I shoudl receive according to shopify's docs.
Can someone please help me with what is going wrong?
Edit: Using Post,I get a type error
const https = require('https');
var data = JSON.stringify(obj)
var options = {
hostname: 'https://{apikey:password}#tuscstore.myshopify.com/admin/api/2020-01',
path: '/products.json',
method: 'POST',
headers: {
'Content-Type': 'application/json',
/*'Content-Length': data.length*/
'Authorization' : 'API_TOKEN'
}
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
});
req.on('error', (e) => {
console.error(e);
});
req.write(data);
req.end();
TypeError: Failed to execute 'fetch' on 'Window': Failed to parse URL from https://[https://{APIKEY:PWD}#tuscstore.myshopify.com/admin/api/2020-01]/products.json
you creating a new product you have to make http POST request , and now your making http GET request you should update your options like so :
const options = {
hostname: 'https://apikey:password#<#store_url>/admin/api/2020-01', // your host name
path: '/shop.json', // your end point
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization' : 'YOUR_API_TOKEN'
}
}
OR you can use this package to solve all your problems https://www.npmjs.com/package/shopify-api-node

pdflayer API post request saying I didnt not provide api_key even though it did

I am currently trying to work with the API from http://www.pdflayer.com, however I am having issues with providing the api_key through a post request with Axios.
My code looks like this:
var config = require('./../config');
var axios = require('axios');
var fs = require('fs');
const BASE_URL = 'http://api.pdflayer.com/api/convert';
module.exports = {
createQuotePdf() {
var data = {
document_url: 'https://www.apple.com',
access_key: config.pdflayer_acccess_key,
page_size: 'A4',
test: '1'
}
axios.post(BASE_URL, data)
.then((data) => {
console.log(data);
fs.writeFile('./download.pdf', data.body, function(err) {
if (err) console.log('error: ', err);
})
});
}
};
However, every time I make the request, it is saying that I did not provide the api key, even though I specified.
It would be great if someone could help me.
Best regards
For anybody having the same issue, here is the working solution:
var config = require('./../config');
var request = require('request');
var BASE_URL = 'http://api.pdflayer.com/api/convert';
var ACCESS_KEY = '?access_key=' + config.pdflayer_acccess_key;
var API_URL = BASE_URL + ACCESS_KEY;
module.exports = {
createPdf() {
var formData = {
document_html: `<html><body>Hello World</body></html>`
}
request.post({url: API_URL, formData: formData, encoding: null}, function optionalCallback(err, httpResponse, body) {
if (err) {
console.log(err);
} else {
// Here you can save the file or do anything else with it
console.log(body);
}
});
}
};
Have you tried appending it directly to your BASE_URL since that seams to be the way they are building it
BASE_URL = ('http://api.pdflayer.com/api/convert?access_key=', YOUR_ACCES_KEY)'

Create GitHub repo from node.js

I have this function in my node project, that should create a new GitHub repository for a specific user:
exports.create_repo = function (repo) {
var options = {
host: "api.github.com",
path: "/user/repos?access_token=" + repo.accessToken,
method: "POST",
json: { name: repo.name },
headers: { "User-Agent": "github-app" }
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
response.on("end", function(){
var json = JSON.parse(body);
console.log(json);
});
});
request.end();
}
Every time I use it, the response is:
{ message: 'Not Found',
documentation_url: 'https://developer.github.com/v3' }
What do I do wrong ?

Categories

Resources