NodeJS receive data from a form, edit and send again - node.js

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 :)

Related

Nodejs - parse response data without parsing as String?

I'm following some tutorials online, and I'm trying to parse a response from an HTTP post call from my node app. My app acts as an interceptor, we make a POST request to the interceptor app, I transform the data, then I post it to another client to perform some action, and then I want to return the response from the other app as my app's response. Below is the code I use to make the post:
const request = http.request(options, function(response) {
console.log('STATUS: ' + response.statusCode);
console.log('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
//res is the actual response object to my app's own post function
res.status(response.statusCode).send({response:chunk});
});
});
Now, the response to the post object looks like ["Hey there! How can I help you?"].
However, when I return that as a response to my API, the body looks like:
"response": "[\"I am doing well. Thank you for asking.\"]\n".
I want to interact with the array that is returned, grab the string at index 0, and return that as my response. Is this possible?
Have you tried?
res.setHeader('content-type','application/json');
res.status(response.statusCode).send(chunk);

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.

How can I use restler to make a GET with a Cookie?

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'.....

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.

nodejs http.request save in global variable

In http://nodejs.org/docs/v0.4.7/api/http.html#http.request
There is an example that fetches some web content, but how does it save the content to a global variable? It only accesses stuff the function.
If look closely at the example, that HTTP request is used to POST data to a location. In order to GET web content, you should use the method GET.
var options = {
host: 'www.google.com',
port: 80,
method: 'GET'
};
The HTTP response is available in the on-event function inside the callback-function which is provided as the parameter for the constructor.
var req = http.request(options, function(res)
{
res.setEncoding('utf8');
var content;
res.on('data', function (chunk)
{
// chunk contains data read from the stream
// - save it to content
content += chunk;
});
res.on('end', function()
{
// content is read, do what you want
console.log( content );
});
});
Now that we have implemented the event handlers, call request end to send the request.
req.end();

Resources