Nodejs - Send data with ajax to server - javascript

I try send the values to my server, but If I try, my console show me the error:
Cannot POST /
I try see other examples, and I try with this codes:
My index.html:
function sendData() {
var latestResponse = Api.getResponsePayload();
var context = latestResponse.context;
var mail = context.email; // I can see the data of these variables perfectly on the console
$.ajax({
type: "POST",
url: "http://localhost:3000/",
crossDomain:true,
dataType: "json",
data:JSON.stringify({email: mail})
}).done(function ( data ) {
alert("ajax callback response:"+JSON.stringify(data));
})
}
My server.js:
'use strict';
var server = require('./app');
var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
server.on('request', request);
server.listen(port, function() {
console.log('Server on port: %d', port);
});
function request(request, response) {
var store = '';
request.on('data', function(data)
{
store += data;
});
request.on('end', function()
{ console.log(store);
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.end(store)
});
}
My repository:
FolderRepository
public
- js folder
- img folder
- css folder
- index.ejs
server.js
app.js

Because your server is running on the other port. This is your port
var port = process.env.PORT || process.env.VCAP_APP_PORT || 3000;
and in ajax request you need to post to the url http://localhost: + your port
And also every time when you receive a request, your request will attach a new event handler to the data event, so after 10 attached events you will get an warning message about the leaking of the memory.
This code works. The main difference is that I call http.createServer() and you get it from the app.js. Look into the app.js and see if the server is created appropriatly.
Try to see if your server is created correctly.
var http = require('http');
var port = 3000;
var proxy = http.createServer();
proxy.listen(port);
proxy.on('request', request);
function request(request, response) {
var store = '';
request.on('data', function (data) {
store += data;
});
request.on('end', function () {
console.log(store);
response.setHeader("Content-Type", "text/json");
response.setHeader("Access-Control-Allow-Origin", "*");
response.end(store)
});
}

Related

Node proxy server modify response after query in database

I am troubling with nodejs proxy server modified(write) response.
I want to achieve auto login for one site via node proxy server and for that i have to query in database then i can modified response but it seems req ended before req.write and getting Error: write after end
Below is my implementation so far.
var express = require('express');
var proxy = require('http-proxy-middleware');
var options = {
target: 'http://example.com/', // target host
changeOrigin: true,
onProxyReq: function onProxyReq(proxyReq, req, res) {
var _write = res.write;
var body = "";
proxyReq.on('data', function(data) {
data = data.toString('utf-8');
body += data;
});
res.write = function (data) {
try{
//I have database query here instead of setTimeout
setTimeout(function(){
/* Modified response here and write */
_write.call(res, data); //can't write because req already end
},3000);
} catch (err) {
console.log('err',err);
}
}
}
}
// create the proxy (without context)
var exampleProxy = proxy(options);
// mount `exampleProxy` in web server
var app = express();
app.use('/', exampleProxy);
app.listen(8080);
Can anyone guide me how to achieve this ?

How to render object from REST response

I want to render to the ui / print to console log some object value from GET response.
I'm using Node JS for my server side and HTML + JS for my client side.
Because my goal is to render data and the request type is cross domain I can't use "fetch" function.
My only alternative to execute it is to send it by "JSONP" dataType.
Actually, the request is sent and the response receives by callback as well, but my code is print "null" to the console and not the response data.
When I've tried to used JSON.parse() it received a "parseerror".
The expected result it's to get only the image tag value (2.0.90) and to print this inside the console log / render it to the UI.
async function uiChecking() {
let index;
const hostsDock = [qa + dockers];
let lengthVal = hostsDock.length;
for (let hostIndxD = 0; hostIndxD < lengthVal; hostIndxD++) {
index = hostIndxD;
let url = hostsDock[hostIndxD];
$.ajax({
url: url,
dataType: 'jsonp',
}).done( function(data) {
console.log("A " + data);
});
}
}
**Server.js **
var express = require('express');
var cors = require('cors');
var app = express();
var path = require("path");
var fetch = require('fetch-cookie')(require('node-fetch'));
var btoa = require('btoa');
var http = require('http');
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (whitelist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
}else{
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, data , corsOptions) // callback expects two parameters: error and options
};
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/view');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('index');
res.render('logo');
res.writeHead(200, {'Content-Type': 'application/json'});
});
// app.get('/products/:id', cors(corsOptionsDelegate), function (req, res, next) {
// res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
// });
app.get('/data/:id', function (req, res, next) {
var opts = {
host: config.alertService.host,
port: config.alertService.port,
method: 'GET',
path: '/DataService/rest/receiveData/' + req.params.id
}
var reqGet = http.request(opts, function (dataResponse) {
var responseString = '';
dataResponse.on('data', function (data) {
responseString += data;
});
var response = {x:[],y:[],z:[],t:[]};
dataResponse.on('end', function () {
var responseObject = JSON.parse(responseString);
var accs = responseObject.data.listPCS;
for(var i in accs){
response.x.push(accs[i].accX);
response.z.push(accs[i].accY);
response.y.push(accs[i].accZ);
response.t.push(accs[i].timestamp);
}
res.jsonp(response);
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error(e);
});
});
if (app.settings.env === 'production') {
app.error(function(err, req, res) {
res.render('new404.html', {
status: 500,
locals: {
error: error
}
});
});
}
app.listen(8033, function () {
console.log('CORS-enabled web server listening on port 8033')
});
You need to iterate through the response to return the result e.g..
$.each(data, function(index) {
console.log(data[index].ui);
console.log(data[index].id); console.log(data[index].Name);
});

Performing POST Request in Separate Node Module with Express

I'm building a web application that processes a post request then performs a POST request to another server, and then redirects the user based on the returned information.
End result is user types in their username and clicks submit --> application process the post, takes the username --> application performs post to external server including the username --> server returns the url of the server the user should be on --> application redirects the user to that application.
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var findUser = require('./findUserInstance')
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
res.sendFile( __dirname + "/" + "index.htm" );
})
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
username:req.body.username
};
var uUrl = findUser.url(response.username);
console.log("redirecting to " + uUrl);
res.redirect(findUser.url(response.username));
res.end(JSON.stringify(response));
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port)
})
findUserInstance.js
exports.url = function(uName) {
var http = require("https");
var uUrl;
var options = {
"method": "POST",
"hostname": "removed",
"port": null,
"path": "removed",
"headers": {
"appkey": "removed",
"content-type": "application/json",
"cache-control": "no-cache",
"Accept": "application/json",
"postman-token": "7d87bcf1-8e11-9717-2f6e-8150a5625acd"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
var jsoncontent = JSON.parse(body);
uUrl = jsoncontent.rows[0].url;
console.log("The following should be: user.instance.url.com)
console.log(jsoncontent.rows[0].url);
return uUrl; //The information that I want to return to server.js
});
});
req.write(JSON.stringify({username: uName}));
req.end();
}
The problem is with returning the information from the external post module to the server.js module so that it can perform the redirect. Currently I have the variable uUrl (which is correctly populated with the URL from the post) returned from the function. However the findUserInstance module returns null.
How can I get the value of uUrl from the findUserInstance module to the server.js module?
#bryan euton good response you should return any object in findUserInstance like promise!
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
exports.url = function(uName) {
return new Promise( function (resolve, reject){
var http = require("https");
var uUrl;
var options = {
"method": "POST",
"hostname": "removed",
"port": null,
"path": "removed",
"headers": {
"appkey": "removed",
"content-type": "application/json",
"cache-control": "no-cache",
"Accept": "application/json",
"postman-token": "7d87bcf1-8e11-9717-2f6e-8150a5625acd"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
var jsoncontent = JSON.parse(body);
uUrl = jsoncontent.rows[0].url;
console.log("The following should be: user.instance.url.com)
console.log(jsoncontent.rows[0].url);
resolve(uUrl); //The information resolve promise with your datas
});
});
req.write(JSON.stringify({username: uName}));
req.end();
});
}
Yes now uurl in server.js is asynchronous change handler:
app.post('/process_post', urlencodedParser, function (req, res) {
// Prepare output in JSON format
response = {
username:req.body.username
};
findUser.url(response.username).then( function(uUrl){
console.log("redirecting to " + uUrl);
res.redirect(findUser.url(response.username));
res.end(JSON.stringify(response));
});
});

Node JS OR Express JS HTTP GET Request

I am using express.js and I need to make a call to HTTP GET request ,to fetch JSON data .Please suggest me some good node js/express js modules/lib to perform get/post request .
Node.js provides an extremely simple API for this functionality in the form of http.request.
var http = require('http');
//The url we want is: 'www.random.com/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.com',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Here I attach some more examples with POST and custom headers. If you don't need special things, I'd stick to the native code.
Besides, Request, Superagent or Requestify are pretty good libraries to use.
var express = require('express');
var app = express();
var fs = require('fs');
app.get('/', function (req, res) {
fs.readFile('./test.json', 'utf8', function (err, data) {
if (err) {
res.send({error: err});
}
res.send(data);
})
});
var server = app.listen(3001, function () {
console.log('Example app listening port 3001');
});

Making HTTP requests and sending a body of data in node.js

I'm currently going through Guillermo Rauchs "Smashing Node.Js" Book. I'm stuck in chapter 7 where the task is to set up a client/server and to send a string from the client to the server over a http connection. The string should be printed from the server.
the client code:
var http = require('http'), qs = require('querystring');
function send (theName) {
http.request({
host: '127.0.0.1'
, port: 3000
, url: '/'
, method: 'GET'
}, function (res) {
res.setEncoding('utf-8');
res.on('end', function () {
console.log('\n \033[090m request complete!\033[39m');
process.stdout.write('\n your name: ');
})
}).end(qs.stringify({ name: theName}));
}
process.stdout.write('\n your name: ');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function (name) {
send(name.replace('\n', ''));
});
the server:
var http = require('http');
var qs = require('querystring');
http.createServer(function (req, res) {
var body = '';
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
res.writeHead(200);
res.end('Done');
console.log('\n got name \033[90m' + qs.parse(body).name + '\033[39m\n');
});
}).listen(3000);
I start the client and the server. The client seems to work:
mles#se31:~/nodejs/tweet-client$ node client.js
your name: mles
request complete!
your name:
However on the server side, it's only showing an undefined:
mles#se31:~/nodejs/tweet-client$ node server.js
got name undefined
According to the book, here should be an "mles" too.
, method: 'GET'
should be
, method: 'POST'
GET requests do not have a body so there is nothing to parse on the server's side.

Categories

Resources