How can I use restler to make a GET with a Cookie? - node.js

I'm trying to make a GET with a Cookie but it's not working in my node.js program. However, the GET works fine from POSTman in chrome. Why could this be? The error I get back is 'Access denied for user anonymous'. I believe that's because this particular API expects a Cookie with session_id=xxxxxxx which I am trying to pass like this:
rest.get(<theurl>, {'headers':{'Cookie':<session_id=xxxx>}}.on('complete'.....
The only thing I can think of is the session_id=xxx is not being correctly put into the JSON object as a variable. But I'm new to node and javascript so I don't know how to debug other than putting console.log() all over the place. Any ideas out there?

Something like this:
var options = {
hostname: 'example.com',
path: '/somePath.php',
method: 'GET',
headers: {'Cookie': 'myCookie=myvalue'}
};
var results = '';
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
results = results + chunk;
//TODO
});
res.on('end', function () {
//TODO
});
});
req.on('error', function(e) {
//TODO
});
req.end();

Cookie without quote, like this:
rest.get(<theurl>, {headers:{Cookie:<session_id=xxxx>}}.on('complete'.....

Related

How to make an https version of a Unirest example

I would like to use the https library in node.js to send a request to this api:
https://rapidapi.com/dimas/api/NasaAPI?endpoint=apiendpoint_b4e69440-f966-11e7-809f-87f99bda0814getPictureOfTheDay
The given example on the RapidAPI website uses Unirest, and I would like to only use the https library. I've tried to write it like this:
const https = require('https');
var link = "https://NasaAPIdimasV1.p.rapidapi.com/getPictureOfTheDay";
var options = {host: "https://NasaAPIdimasV1.p.rapidapi.com/getPictureOfTheDay",
path: "/", headers: {"X-RapidAPI-Key": "---MY KEY(Yes, I've replaced it)---", "Content-Type": "application/x-www-form-urlencoded"}}
https.get(link, options, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
console.log(data);
});
}).on("error", (err) => {
console.log("https error 4: " + err.message);
});
But that returns the following response:
{"message":"Endpoint\/ does not exist"}
Thanks for any help
There are several mistakes.
First, you essentially pass URL in https twice - first as link param, second as combination of host and path properties for options param.
Second, your host is actually the full path - but it shouldn't be. In the end, looks like the library got confused and sent request to https://NasaAPIdimasV1.p.rapidapi.com/ instead.
Finally, this particular API requires using 'POST', not 'GET' method. That's actually mentioned in the documentation. That's why you have 'endpoint does not exist' error even on correctly formed request.
One possible approach is dropping link altogether, sending URL as part of options:
var options = {
host: 'NasaAPIdimasV1.p.rapidapi.com',
method: 'POST',
path: '/getPictureOfTheDay',
headers: {/* the same */}
};
https.request(options, (resp) => { /* the same */ }).end();

TypeError: Request path contains unescaped characters, any idea

//route to search (POST http://localhost:8080/api/search)
apiRoutes.post('/search', function(req, res) {
console.log('search');
var query = req.params;
console.log(query);
options = {
protocol : "https:/",
host: "https://api.themoviedb.org",
path: "/3/search/movie?api_key=35f7a26be584f96e6b93e68dc3b2eabd&language=en-US&page=1&include_adult=false&query="+query,
};
var req = https.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());
});
});
req.write("{}");
req.end();
})
DOES ANYONE KNOW WHERE THE PROBLEM IS?
I'm trying to do a request to do a research to the api the movie db and get the result back
There are some problems with the code. I have tested it and made it to work.
let options = {
host: "api.themoviedb.org",
path: "/3/search/movie?api_key=35f7a26be584f96e6b93e68dc3b2eabd&language=en-US&page=1&include_adult=false&query="+query.data.replace(' ','%20'),
};
first of all since you are using https module you don't need to specify the protocol nor you need to put it in the url. That's how your options variable should be.
Second you are appending the entire query object to the url which is {} instead you should append a string which will be in one of the key of your query object in my case its query.data
Third if there are spaces in the string Eg: Home Alone you to maintain space and avoid the error we replace the string with %20 which is a escaping character.
Forth Try giving a unique name for https request variable and its response variable in the callback function or it will override the route's req res variables cause your code to not work. Notice how I have used route's res function to send the data back and end the response
Also I am getting the data in req.body and you are using req.params however there are no params defined in your routes. Try going through the documentation for more information
Here is the complete code
apiRoutes.post('/search',function (req, res) {
https = require('https');
var query = req.body;
console.log(query.data);
let options = {
host: "api.themoviedb.org",
path: "/3/search/movie?api_key=35f7a26be584f96e6b93e68dc3b2eabd&language=en-US&page=1&include_adult=false&query="+query.data.replace(' ','%20'),
};
var request = https.request(options, function(response) {
var chunks = [];
response.on("data", function (chunk) {
chunks.push(chunk);
});
response.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
res.send(body);
res.end()
});
});
request.end();
});
Hope it helps.

408 Timeout in NodeJS app requesting Github API

Following the documentation of the Github API to create an authorization for a NodeJS app.
I have the following code:
var _options = {
headers: {
'User-Agent': app.get('ORGANISATION')
},
hostname: 'api.github.com'
};
var oauth2Authorize = function () {
var path = '/authorizations?scopes=repo';
path += '&client_id='+ app.get('GITHUB_CLIENT_ID');
path += '&client_secret='+ app.get('GITHUB_CLIENT_SECRET');
path += '&note=ReviewerAssistant';
_options.path = path;
_options.method = 'POST';
var request = https.request(_options, function (response) {
var data = "";
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log(data);
});
});
request.on('error', function (error) {
console.log('Problem with request: '+ error);
});
};
And all I get is:
408 Request Time-out
Your browser didn't send a complete request in time.
Doing a GET request works though.
http.request() doesn't immediately send the request:
With http.request() one must always call req.end() to signify that you're done with the request - even if there is no data being written to the request body.
It opens the underlying connection to the server, but leaves the request incomplete so that a body/message can be sent with it:
var request = http.request({ method: 'POST', ... });
request.write('data\n');
request.write('data\n');
request.end();
And, regardless of whether there's anything to write() or not, you must call end() to complete the request and send it in its entirety. Without that, the server will eventually force the open connection to close. In this case, with a 408 response.

NodeJS receive data from a form, edit and send again

Basically I receive the values from a form with the function event:
var formData="";
req.on('data', function (chunk){
formData += chunk;
});
And I send those values again in another http.request:
req.on('end', function (){
var options = { port: conf.port, path: req.path,
host: conf.host, method: req.method , headers: req.headers};
authReq = http.request(options,
function (response){...});
authReq.write(formData);
authReq.end();
});
What I want is to add more data to the form receive from the previously form, like for example something like this:
var formData="client_id=XXX&client_secret=XXX&";
req.on('data', function (chunk){
formData += chunk;
});
But this is not working, after made the authReq.write(formData); looks like the data send is empty or wrong.... any suggestion ?
In the second request, the variable formData filled in the first request, will be empty.
You might need to use a session. (http://expressjs-book.com/forums/topic/express-js-sessions-a-detailed-tutorial/)
Also, from the looks of your code snippets, I suggest you look into http://passportjs.org/ for authentication :)

How to post the data in Node js

In my application i need to post the dynamic data into my main page(mani page means if i run my url(localhost:3456) in browser means that will display one page na that page).How can i post that data.I have tried this but i couldn't post the data.Can anyone help me to fix the issue.
app.js
var http = require('http');
var server = http.createServer(function(req, res){
res.writeHead(200, ['Content-Type', 'text/plain']);
res.write('Hello ');
res.end('World');
});
server.listen(3456);
postdata.js
var data={"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-0402T11:50:22.167Z"}
var options = {
host: 'localhost',
port: 3456,
path: '/',
method: 'POST',
data:data,
header: {
'content-type': 'application/json',
'content-length': data.length
}
};
var http=require('http');
var req;
req = http.request(options, function(res) {
var body;
body = '';
res.on('data', function(chunk) {
body += chunk;
});
return res.on('end', function() {
console.log('body is '+body);
});
});
req.on('error', function(err) {
console.log(err);
});
req.write(data);
req.end();
Do you have express installed along with Node, if so you can set up Rest Api's which you can use them in your jQuery and bind data dynamically. Please try to look into
http://expressjs.com/
Hope this helps.
//this is a string
var jsonString = '{"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-04-03T05:29:15.521Z"}';
//this is an object
var jsonObj = {"errorMsg":{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-04-03T05:29:15.521Z"};
note the single quotes in for string
request.write(chunk, [encoding]) requires chunk to be either Buffer or string (see: http://nodejs.org/api/http.html#http_request_write_chunk_encoding)
Two things. First:
var data={"errorMsg:{"errno":34,"code":"ENOENT","path":"missingFile.txt"},"date":"2013-0402T11:50:22.167Z"}
is missing a double-quote, so it's invalid syntax... hence why the syntax highlighting is having trouble.
Second:
req.write(data);
should be:
req.write(JSON.stringify(data));
EDIT:
Based on your comment, I think you might be asking how to read from the body of an HTTP POST request (you're question is very ambiguously worded). If so, that's already very well documented in the Node.js API. Something along the lines of:
var server = http.createServer(requestHandler);
server.listen(3456);
function requestHandler (req, res) {
req.setEncoding('utf8');
var body = '';
req.on('data', function (chunk) { body += chunk; });
req.on('end', function () {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('The body of your request was: ' + body);
});
}
If that's not what you're asking, you'll need to clarify your question. Terms like 'main page' have no meaning unless you explicitly define what they are and what the expected outcome is.

Resources