I'm new to Node.Js, and I have written two methods post and get. First of all I want the post to look like the get request (asynchronous function) so I can export it from a different js file, but I'm not sure if it is asynchronous right now. Second, I want the get request to be able to send a cookie with the url also.
here is the scenario:
1- send a post request and set the cookie. The server will direct me to another location.
2- get the location and send a get request and include the cookie.
here is my code for POST:
request.post({
headers: { 'content-type': 'application/x-www-form-urlencoded' },
url: 'http://example/login',
body: 'mes=heydude',
followRedirect: true,
form: {
username: 'usr',
password: 'pass'
}
}, function (error, response, body) {
if (error) {
console.log(error)
}
var setCookie = response.headers['set-cookie']
console.log('login success')
console.log(body)
})
This method works fine but how to make it an asynchronous function? like the below get request? also how to make the get request returns the cookie and the html?
function fetch (url, callback) {
return new Promise(function (resolve, reject) {
request(url, function (error, response, html) {
if (error) {
return reject(error)
}
if (response.statusCode !== 200) {
return reject(new Error('error code'))
}
return resolve(html)
})
})
}
If there is ane module that can do that on NPM let me know thanks.
Help a newbie and get a trophy!
If you are using Express, you should look at cookie-parser. This is a library that handles cookies (as the name suggests) so you don't have to reinvent the wheel.
If you don't know what Express is, I suggest you to look at it.
Express is a minimal and flexible Node.js web application framework
that provides a robust set of features for web and mobile
applications.
Related
I have been stuck with a weird issue with CORS for quite some time now. To explain the setup I have a frontend JS snippet (including fetch API call to my own server) which I want to use as an embed code snippet other web applications can use. (ex: kind of like google analytics)
// JS snippet to copy to an unknown website
<script>
// extract data and add to the body
const extracted_data = {}
fetch("https://api.xxxx.com/xxxxxx/create", {
method: "POST",
mode: 'cors',
body: JSON.stringify(extracted_data),
referrer: "origin",
headers: {
'Content-Type': 'application/json',
},
})
.then(function (response) {
// The API call was successful!
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (data) {
// This is the JSON from our response
console.warn("Successfull!", data);
alert("Success:" + JSON.stringify(data));
})
.catch(function (err) {
// There was an error
console.warn("Something went wrong ->", err);
alert("error:" + err.message);
});
</script>
The problem is even if I have set my fetch API as below and the correct CORS headers are in my preflight response from my API it works only when the API call resolves immediately. If the API takes more time Fetch throws this common error even if the preflight is successful.
TypeError: Failed to fetch
I verified it using adding the below code to my API. Then it stops working and throws the above error. When I don't have any time taking functions inside my API call it works without errors.
// 10 sec delay to check async behavior of the API
await new Promise(resolve => setTimeout(resolve, 10000));
Any recommendations on how I should proceed to resolve this?
I've been stuck on this issue for some time now, I am trying to subscribe to Linkedin's webhook using ngrok for testing on localhost, and have been trying for some time now, i have tried using encode uri's as well but still running into error, I have verified that the APP_ID, profileId and organizationId i'm using are correct, but still i get the same error. I have also tried using the Restli protocol that linkedin suggests in their documentation but to no avail.
let url = `https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)`;
return new Promise((resolve, reject) => {
request(
{
url,
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`,
// 'X-Restli-Protocol-Version': '2.0.0',
},
json: {
webhook: "https://url.ngrok.io/api/v1/webhook/linkedin/callback"
},
},
(err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
},
);
});
I have been receiving this error constantly no matter what I try, I have tried sending the url like this:
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn:li:developerApplication:{${config.IN.APP_ID}},user:urn:li:person:{${profileId}},entity:urn:li:organization:{${organizationId}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
https://api.linkedin.com/v2/eventSubscriptions/${encodeURIComponent((developerApplication:urn:li:developerApplication:${config.IN.APP_ID},user:urn:li:person:${profileId},entity:urn:li:organization:${organizationId},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS))
All I receive is this error
'{"serviceErrorCode":100,"message":"Unpermitted fields present in RESOURCE_KEY: Data Processing Exception while processing fields [/key]","status":403}'
Any help would be appreciated, I have been stuck on this for a while now.
The request seems to be OK , but the method should be GET (not PUT)
One thing is to check which ID are you using for application_id. The application ID is the one in the url - https://www.linkedin.com/developers/apps/<id from here>/settings
. You need to use and uncomment the header for Restli.
I'd say that your url needs to look like this, as this is from their original POSTMAN collection.
https://api.linkedin.com/v2/eventSubscriptions/(developerApplication:urn%3Ali%3AdeveloperApplication%3A{{application_id}},user:urn%3Ali%3Aperson%3A{{person_id}},entity:urn%3Ali%3Aorganization%3A{{organization_id}},eventType:ORGANIZATION_SOCIAL_ACTION_NOTIFICATIONS)
You can validate here, their full collection - https://www.postman.com/linkedin-developer-apis/workspace/e781b3ac-4101-4d60-8981-afcb4812623d/request/16069442-9d0bf046-ea81-4af0-9515-d07246a0ab39
LinkedIn webhooks does not support ngrok URIs
Not able to send response of a REST api callout to browser page using NodeJs server with Express and Request module.
I understand that due to asynchronous nature of callback method, response of api callout cannot be returned in typical style.
I have tried res.send method, but it gives error res.send is not a function.
Below is sample piece of that I have tried.
const options = {
url: endPoint,
method: 'POST',
headers: {
'Authorization': 'Basic',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Accept-Charset': 'UTF-8'
}
};
request(options, (err, res, body) => {
if (err) { return console.log(err); }
//want to send this body to the page.
console.log(JSON.stringify(body));
res.send(body);
});
It gives this error message,
res.send(body);
TypeError: res.send is not a function
at Request.request [as _callback]
Figured the issue.
First problem was as #vipul pointed above. res was response of callout and not instance of global HttpResponse object, so send method was not available on that object. I changed the method,
request(options, (err, response, body) => {
if (err) { return console.log(err); }
//want to send this body to the page.
console.log(JSON.stringify(response.body));
// using the HttpResponse in global context.
this.res.send(JSON.parse(body));
});
Then I faced below error,
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client]
Problem was while making the callout, I was returning the response right after callout method.
.get('/authorize', (req, res) => {
console.log('Authorize Hit! '+req.query.code);
try {
//TODO: Need to utilize state to the current flow in action.
let flowDetails = flow.flowMap.get('wsf');
if(flowDetails) {
//this method makes REST API call
flowDetails.refreshToken(req, res);
//this line was the problem!! Removed it to fix the error.
res.send('Refresh Token Completed!');
}
} catch (error) {
(Object.keys(error).length === 0)?res.send(error.message):res.send(error);
}
})
But due to asynchronous nature of callback function, by the time callout response was received, actual request/response was already returned and request was completed. So removed the res.send right after callout to fix the issue.
Hopefully it will be helpful for others as well :)
I want to send some post data to an api
10.11.12.13/new/request/create
this is an API to create a new request in portal. now I am making one application in NodeJs and want to create request from node js application.
now I have to send in this format
{"user":"demo", "last_name":"test","contact":"989898989"}
so how can I send data on above url to create a new request.
I am a beginner in NodeJs and don't have much idea.
any help will be appreciated.
Thanks in advance
I would recommend to use axios or any other request lib :
const axios = require('axios');
axios.post('10.11.12.13/new/request/create', {
user: 'demo',
last_name: 'test',
contact: '989898989',
});
here is an example using request module
var headers = {
'Content-Type': 'application/json'
}
var options = {
url: "10.11.12.13/new/request/create" ,
method: 'POST',
headers: headers,
json: true,
body: {user:"demo", last_name:"test",contact:"989898989"}
}
request(options, function (error, response, body) {
if (error) {
//do something
}
console.log(body)//do something with response
})
You can use postman REST client for GET method using your URL and Body (which you want to post) and click on * Code * and select NodeJS and their you will find code generated for you to work with. Here is the link https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets
With my experience, it is good to start with Request package for node js. Here is the link for your reference: https://www.npmjs.com/package/request
I'm making an API call (specifically to stubhub) and I want to get the response headers found in the browser network tab:
Here's my API call (using Meteor HTTP)
HTTP.post('https://api.stubhub.com/login', {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64
},
params: {
'grant_type' : 'password',
'username' : username,
'password' : password,
'scope' : 'PRODUCTION'
}
}, function(err, res) {
if (err) {
console.log(err)
} else {
console.log(res);
}
})
I console.log 'res' to see everything, and I saw a few objects but main ones are header and data. Data is the content object which is usable in other ways, but header just returns this:
How do I get the Response Headers?
Figured it out. I was making this call client-side (obviously not secure, just to get my app up and running/testing). If you make the call server-side, say via a Meteor method, the full header field will be available in the response.