From one of the machines in my network (client), I am making $.ajax() request to my Nodejs server like,
//Client : index.html
$.ajax({
type:"post",
url:'http://192.168.2.6:8080',
data:JSON.stringify({"loginData":{"uanme":"maverick","upass":"asd"}}),
success:function(data){console.log(data);alert(data);},
error:function(){alert('Error aala');}
});
AND my Nodejs server is
//listener.js
var server = require('http').createServer(function (request, response) {
var body='';
if(request.method=='POST'){
request.on('data',function(data){
body+=data;
});
request.on('end',function(){
console.log(body);
});
}
}).listen(8080);
These console.log()s are working absolutely fine. I get the exact same data I am sending on the node side,
Now my question is, in php when we make an $.ajax() request, we use echo in our php file to send the data back to the client,
What should I have to do on server side in Nodejs (listener.js file) if I want to send the data back to the client?
var server = require('http').createServer(function (request, response) {
var body='';
if(request.method=='POST'){
request.on('data',function(data){
body+=data;
});
request.on('end',function(){
console.log(body);
//response.setHeader("Content-Type", ""); set the header to your content type
response.write('foo'); // <-----
response.end('Dear client, I have cake for you'); // <-----
});
}
}).listen(8080);
Further reading Node.js Documentation
Solved this problem myself.
The problem was with cross domain ajax requests.
I don't know why this was happening, even though I had specified url:localhost:8080 in my $.ajax call...
Solved the problem my adding
response.setHeader("Access-Control-Allow-Origin", "*");
in my response headers.
PEACE
Related
I have some middleware functions in my Express app which make outgoing request to a separate server and then send the response returned back to the client.
So this kinda thing:
var request = require('request'),
helpers = require('./helpers.js');
//GET
module.exports.fetch = function(req, res) {
var options = helpers.buildAPIRequestOptions(req);
request(options, function(err, response, body){
res.status(response.statusCode).send(body);
});
};
I am looking at writing unit tests and would like to mock out and return my own responses when the outgoing requests withing these functions gets fired.
I have come across supertest and have had a go at writing a suite like so:
var app = require('./index.js'),
request = require('supertest')(app),
should = require('should');
//GET
describe('GET requests', function(){
it('should do something', function(done){
request
.get('/api/schemes')
.expect(200, done)
.end(function(err, res){
// console.log(res);
// console.log(err);
res.status.should.equal(200);
});
});
});
I think I need something like sinon here, so I could spy on a request that would hit my middleware function and return a response of my choosing. I am just struggling to understand how to add the stubbing to my test.
Can someone advise further please?
Thanks
node-nock can record requests made via the http module (and so, by proxy, request). These can then be queued for replaying in your test suite. The GitHub page has great documentation.
I am doing a post request from my server to another server and for it i'm using the library https://github.com/request/request.
So, I use the next code:
router.post('/extern/*', function(req, res, next) {
var path = req.params['0'];
var input = req.body.text;
var encript = crypto.encrypt(input);
request.post(config.petitionServer + path).form({data: encript}).pipe(res)
});
The session has been initialized before calling this post, but when it executes, the session is reseted. So, in this case, I lose the csrf code from the session var.
The error is in the 'pipe' function, because if I call it I lose the session, not in other case, but I need to use it.
How can I use the pipe function without lose the actual session?
I believe express-session is saving it's sessions into cookies and what you are doing is piping the hole response from config.petitionServer + path to client so it overwrites cookies that the express-session has saved. Maybe it would be a better idea just to pipe the body of the respone?
router.post('/extern/*', function(req, res, next) {
var path = req.params['0'];
var input = req.body.text;
var encript = crypto.encrypt(input);
request.post({url: config.petitionServer + path, formData: {data: encript}, function(err, httpResponse, body))
res.send(body);
});
As mentioned in other answers, your express session is getting reset by the cookie that is sent from the other server.
There's a couple of ways you could solve this problem. If you don't need the cookie from your petition server, you could delete the header before you pipe the response:
router.post('/myServerUrl', function(req, res) {
request.post('/remoteServerUrl', { data })
.on('response', function(response) {
delete response.headers['set-cookie'];
})
.pipe(res);
});
If you don't want to modify any headers, you should be able to pipe the response inside of the response handler along with the content type.
router.post('/myServerUrl', function(req, res) {
request.post('/remoteServerUrl', { data })
.on('response', function(response) {
res.set('Content-Type', 'image/jpeg')
response.pipe(res);
});
});
I founded the solution and it was my bad.
Session is in req.session and the petition server was using also the express-session module. When request was received by petition server, this one replaced the session var by the one of the petition server.
The solution was to remove express-session module from petition server.
Anothe solution could be manage the session from the host server preventing to replace it. But I didnt do it
Mechanism :
I am making this POST request to my API :
request.post('http://localhost:9876/api/alerts',{body: "test"}, function (err, res, body) {
if (err) {
self.emit('log','ERROR : API error - '+err);
}
self.emit('log','RESPONSE - '+res.statusCode);
});
On the server side, I have :
app.post('/api/alerts',function(req,res){
console.log(req);
res.status(200).send('OK');
});
Communication is made and it returns a 200 status. But on the server side, I see no trace of my request's body.
The full 'req' log is available here : https://gist.github.com/xShirase/0f9de0048e5cfa40a98c , the most relevant part being :
body: {},
I was wondering if it was coming from the Passport middleware that I use to secure the rest of my routes, or if I just botched the client request...
I have tried many different requests formats on the client side, and nothing has worked, and I have very little experience with Passport, so please let me know where my problem comes from.
Unless you have a (custom) middleware earlier up in the route/middleware chain that is doing something like:
app.use(function(req, res, next) {
var buffer = '';
req.setEncoding('utf8');
req.on('data', function(d) {
buffer += d;
}).on('end', function() {
req.body = buffer;
next();
});
});
then you probably shouldn't expect req.body to be populated since the common body parsing modules expect a Content-Type of one of application/json, application/x-www-form-urlencoded, or multipart/form-data. Your request() doesn't seem to be setting any of these, which really is correct since it's just free-form data, but that means no middleware is reading request data.
I'm using MEAN stack with MeanJs. The thing is, I have a task that requires calling a GET request from the server side (Expressjs) to another server (with a different domain name).
The code in the client side (AngularJs) calls:
$scope.getWorkflow = function() {
$http.get('/ezee', $scope.credentials).success(function(response) {
console.log(response.message);
}).error(function(response) {
console.log('error');
});
};
And the corresponding server controller function is:
exports.list = function(req, res) {
req.get('http://ezslave.io', function(q, r){
res.json({message: r.message}); // just to test
});
};
Obviously, the code below doesn't work. I'm unsure about how to make a GET request from that list function. Am I supposed to use ExpressJs or pure NodeJs for this? And how to get the correct library loaded?
Use the request module of nodejs : https://github.com/mikeal/request
for sending the http request.
var request = require("request");
exports.list = function(req, res) {
request("http://ezslave.io",function(err,response,body){
res.send(response);
});
};
Hope this helps you
I'm trying to make a simple form, with user name and last name, and when the user submit information, another page is displayed. I did a form in html, but I'm not sure about what to do next? Does anyone have a small, self-contained example of a form, using node js?
This example does not quite complete your task. But it is a self contained node.js program that displays a form and a different page upon form receipt.
Copy it into a file and then run node filename.js and then go to http://localhost:3000 in a browser.
Take note of the asynchronous code structure. I define a handler function but don't execute it immediately. We instead pass the function to http.createServer and then call .listen(3000). Now when an HTTP request comes in, the http server will pass a req, res pair to the handler function. req is the request object (this will contain the form data; see this question for some hints on how to get that data out. (I suggest that you jump right in and build a small Express app. It's a really nice framework.)
//app.js
// Load the built in 'http' library
var http = require('http');
var util = require('util');
// Create a function to handle every HTTP request
function handler(req, res){
if(req.method == "GET"){
console.log('get');
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end("<html><body><form action='/' method='post'><input type='text' name='hello'><input type='submit'></form></body></html>");
} else if(req.method == 'POST'){
console.log('post');
// Here you could use a library to extract the form content
// The Express.js web framework helpfully does just that
// For simplicity's sake we will always respond with 'hello world' here
// var hello = req.body.hello;
var hello = 'world';
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.end("<html><body><h1>Hello "+hello+"!</h1></body></html>");
} else {
res.writeHead(200);
res.end();
};
};
// Create a server that invokes the `handler` function upon receiving a request
// And have that server start listening for HTTP requests
// The callback function is executed at some time in the future, when the server
// is done with its long-running task (setting up the network and port etc)
http.createServer(handler).listen(3000, function(err){
if(err){
console.log('Error starting http server');
} else {
console.log('Server listening on port 3000');
};
});