I am still new to Node Js. Please help me out.
I am calling a web service and based on its results I need to call another web service. The code is given below, however, I am not sure how to call the second web service (ex: foo()).
The 2nd method (That calls the 2nd web service) accepts 2 parameter:
Subject
Body
I need to call the web service 'https://somenew.com/v1/', and need to pass the following as headers as well :
`Content-Type : application/json`
Then As the body I need to pass the following properties :
"name": "My name is alex",
"gender": ["All"],
"Subject": "french",
"Body": "men",
"arrayOfLikes": {"sf": "tennis"}
// 1st Method
app.post('/createthehospital/',function(req,res){
var hos = req.body;
Hos.create(hos, function(err,hos){
if(err){
// Do nothing
} else {
foo('Subject', 'Body'); // CALLING NEW METHOD
}
}
})
});
// 2nd Method
function foo(subject,body) {
app.post('https://somenew.com/v1/',function(req,res){
});
}
You need to use request module
var request = require('request');
request.post({
url: 'https://somenew.com/v1/',
headers: {
'content-type': 'application/json',
},
json: {
"name": "My name is alex",
"gender": ["All"],
"Subject": "french",
"Body": "men",
"arrayOfLikes": {
"sf": "tennis"
}
}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // your response body
}
})
the mistake you have made use express instance app to make call to external url that is not possible use above module to do so.
Related
**I am met with this error when calling a register_url, **
{"Envelope":{"encodingStyle":"http://schemas.xmlsoap.org/soap/encoding/","Body":{"Fault":{"faultcode":"soap:Server","faultstring":"Execution of ServiceCallout SC-SearchURL failed. Reason: ResponseCode 503 is treated as error","faultactor":{},"detail":{"source":{"errorcode":"steps.servicecallout.ExecutionFailed"}}}}}}{"Envelope":{"encodingStyle":"http://schemas.xmlsoap.org/soap/encoding/","Body":{"Fault":{"faultcode":"soap:Server","faultstring":"Execution of ServiceCallout SC-SearchURL failed. Reason: ResponseCode 503 is treated as error","faultactor":{},"detail":{"source":{"errorcode":"steps.servicecallout.ExecutionFailed"}}}}}}
Here is the code
router.get ('/register', getaccess_token,(req, res)=>{
let url = "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl";
let auth = "Bearer "+ req.access_token;
request(
{
url :url,
method : "POST",
headers:{
"Authorization":auth
},
json:{
"ShortCode": "600730",
"ResponseType": "Completed",
"ConfirmationURL": "https://be71-196-207-148-228.ap.ngrok.io/daraja/confirmation",
"ValidationURL": "https://be71-196-207-148-228.ap.ngrok.io/daraja/validation"
}
},
function (error, response, body) {
if (error) {
console.log(error);
} else {
res.status(200).json(body);
}
}
)
});
getaccess_token, is a a function that calls an access token
I have changed the short code that didn't work
2 I have made hosted the confirmation/validation url and made sure its https
3 I have gone to the docs but
Im trying to update a distribution list by sending a put request, when I run this code and test it in postman by giving it a JSON body I get this error in my node.js terminal stating SyntaxError: Unexpected end of JSON input ... any idea what I should change?
My PUT API request
app.put("/api/Dls/Add/:groupId" , (req, res) => {
const response = {
success: false
};
if (Authorized.myToken) {
response.success = true;
response.data = {};
var options = {
method: 'PUT',
url: 'https://SomeAPI.com/' + req.params.groupId,
headers:
{
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + Authorized.myToken
},
body: JSON.stringify(req.body)
};
request(options, function (error, response, body){
if (error) {
console.log(error);
return;
}
const data = response.body;
const dls = JSON.parse(data)
return res.json(dls);
});
}
});
JSON body I'm passing through postman to test the API call
{
"groupId": "123456789",
"SomeField1": null,
"SomeField2": "xxxxxxxxx",
"SomeField3": true,
"SomeField4": "xxxxxxxxx",
"SomeField5": "xxxxxxxxx",
"SomeField6": [
"xxxxxxxxx"
],
"SomeField7": "xxxxxxxxx",
"SomeField8": "xxxxxxxxx",
"SomeField9": "xxxxxxxxx",
"SomeField10": "xxxxxxxxx",
"SomeField11": [],
"SomeField12": "xxxxxxxxx",
"SomeField13": null,
"SomeField14": false,
"SomeField15": ["xxxxxxxxx"]
}
Any feedback is appreciated!
If the JSON that you posted here is the real one that you pass via postman then, it is not the valid JSON as you have the same name properties. When I say valid it means you get something like this after posting to the endpoint.
{
"groupId": "123456789",
"SomeField": [
"xxxxxxxxx"
]
}
Request npm package is also deprecated so it is better to not use it and replace it with something like Axios. TBH I did not see any error in the code that causes the error that you mentioned, do you have access to the API to check the logs? Maybe something went wrong on the https://SomeAPI.com/ endpoint.
I figured out what the issue was, I needed to add the .end to the return statement
ex. return res.status(200).end()
When I create document library in SharePoint via Client REST APIs I get different fields to identify library (like Title, EntityTypeName, Id). Sample response when I create library named "Школьные материалы 2.":
{
"d": {
"__metadata": {
"id": "https://somesite.sharepoint.com/sites/Team_49de5296/_api/Web/Lists(guid'd94587ec-ff65-4b61-b0e8-2a00513494ee')"
…
},
…
"DocumentTemplateUrl": "/sites/Team_49de5296/2/Forms/template.dotx",
…
"EntityTypeName": "2",
"Id": "d94587ec-ff65-4b61-b0e8-2a00513494ee",
"ParentWebUrl": "/sites/Team_49de5296",
"Title": "Школьные материалы 2."
}
}
Though when I go to the SharePoint portal the URL for the library is https://somesite.sharepoint.com/sites/Team_49de5296/2/Forms/AllItems.aspx. Platform that I use supports only listUrls and for my library it is "/sites/Team_49de5296/2". How can I get it from the Create Document Library Response? Should I do separate query to get it? What property would it be?
Yes, its not available in the Created list response.
But you can get it from a deferred property called RootFolder which will have a URL to make that request . It is not available by default for performance reasons.
So, you can modify from below sample code:
var siteUrl = _spPageContextInfo.webAbsoluteUrl;
var fullUrl = siteUrl + "/_api/web/lists";
$.ajax({
url: fullUrl,
type: "POST",
data: JSON.stringify({
'__metadata': { 'type': 'SP.List' },
'BaseTemplate': 100,
'Title': "Test JS List"
}),
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data){
console.log(data);
// get the RootFolder endpoint
var listRootFolderEndpoint = data.d.RootFolder["__deferred"]["uri"];
$.getJSON(listRootFolderEndpoint, function( rootFolderListData ) {
// Make a GET request and then get data
console.log(rootFolderListData);
var listServerRelativeUrl = rootFolderListData.ServerRelativeUrl);
});
},
error: function(data){
console.log(data);
}
});?
I have a Lambda proxy integration enabled, and setting the response headers as part of Lambda output and API Gateway that will return them as part of the HTTP response to the client.
Sample code:
callback(null, {
"statusCode": 302,
"Location" : "https://somewebsite.com"
"headers": { "headerName": "headerValue", ... },
"body": "..."
});
I need to send out 3 cookies in the headers. I tried. But, failed:
callback(null, {
"statusCode": 302,
"Location" : "https://somewebsite.com"
"headers": { "Set-Cookie": [cookie1String, cookie2String, cookie3String] },
"body": "..."
});
[Edit]
I concatenated the cookie and passed in as the response, the client gets the cookie. But when the client calls the target in "location", the request does not have the cookie in the header.
callback(null, {
"statusCode": 302,
"Location" : "https://somewebsite.com"
"headers": { "Set-Cookie": c1=cookie1String;c2=cookie2String; c3=cookie3String] },
"body": "..."
});
Please help in sending these 3 cookies out to my client.
Use multiValueHeaders instead of headers.
const response = {
isBase64Encoded: true,
statusCode: 200,
multiValueHeaders : {"Set-Cookie": [`language=${language}`, `theme=${theme}`]},
body: JSON.stringify('User profile set successfully')
};
callback(null, response);
If you need it to be smarter, consider something like
function createHeaders(headers) {
const defaultHeaders = {
'Access-Control-Allow-Origin': '*',
};
const allHeaders = Object.assign({}, defaultHeaders, headers);
const singleValueHeaders = {};
const multiValueHeaders = {};
Object.entries(allHeaders).forEach(([key, value]) => {
const targetHeaders = Array.isArray(value) ? multiValueHeaders : singleValueHeaders;
Object.assign(targetHeaders, { [key]: value });
});
return {
headers: singleValueHeaders,
multiValueHeaders,
};
}
Then use it in the callback function.
callback(null, {
statusCode: status || 200,
body: JSON.stringify(body),
...createHeaders({ 'Set-Cookie': cookie }),
});
API gateway does not let you map the same header more than once. I got around by using different casing to set-cookie method.
callback(null, {
"statusCode": 302,
"Location" : "https://somewebsite.com"
"headers": { "Set-Cookie": cookie1, "set-Cookie": cookie2 },
"body": "..."
});
I would say that your issue is related to the fact that your response object in the callback is not formatted the way the api gateway expects.
These links reference aws documentation specifically to that.
http://docs.aws.amazon.com/apigateway/latest/developerguide/handle-errors-in-lambda-integration.html
Issue with your code...
'location' does not look like a valid property
Make sure your header key/value pairs are actual JSON objects using something like JSON.stringify
Don't forget to enable logs for both api gateway and lambda with full requests and responses. These two logs will help you debug.
I've been trying to whitelist my domains following the instruction that is given by facebook but nothing is working.
I first tried with curl, the response is {result:"success"} but when I try to list the domains that are whitelisted I am getting {data:[]}
Then I tried using node request module as follow:
request.post("https://graph.facebook.com/v2.6/me/messenger_profile?access_token=sfdlksdfu79r9429049824982342348sjdfsf", {
"setting_type": "domain_whitelisting",
"whitelisted_domains": ["https://mydomainw.com", "https://mydomainw.com/profile", "https://sfujyx.com/ofr", "mydomain1.com", "mydomain.com"],
"domain_action_type": "add"}, function (err, res, body) {
console.log("Whitelisting domain");
if (!err) {
console.log(body);
console.log("Showing the list of whitelisted:");
request.get("https://graph.facebook.com/v2.6/me/messenger_profile?fields=whitelisted_domains&access_token=sfdlksdfu79r9429049824982342348sjdfsf", function (err, res, body) {
if (!err) {
console.log(body);
} else {
console.log(err);
}
});
} else {
console.log(err);
}
});
Still it bring the same result as curl :
And when I use Facebook Graph Api Explorer tool, here is the error I am getting:
I am really stuck, I don't know what should I do or how people exactly whitelist domain for messenger extension.
What I am doing wrong? why isn't the domains being added?
My project is on Google App Engine.
The problem is I was using the App Access Token instead of the Page Access Token, I didn't know the difference.
your domain: "https://mydomainw..com" is an invalid domain.
The request should return:
{
"error": {
"message": "(#100) whitelisted_domains[0] should represent a valid URL",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "Aq3AVaNVJU9"
}
}
Actually, I didn't use "setting_type" before. This is how I register domains:
var request = require("request");
var options = { method: 'POST',
url: 'https://graph.facebook.com/v2.6/me/messenger_profile',
qs: { access_token: 'my_page_token' },
headers: { 'content-type': 'application/json' },
body:
{ whitelisted_domains:
[
'https://mydomainw.com',
'https://ijuugwivbc.localtunnel.me' ] },
json: true };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});