I have the following node express function:
var express = require('express');
var app = express();
// Listen on port 8000, IP defaults to 127.0.0.1
var server = app.listen(8000, function() {
console.log("node express app started at http://localhost:8000");
});
app.get("/test",
function(error, request, response, next) {
request.set("Content-Type", "text/html; charset=UTF-8");
if (error) {
request.status(403);
return next();
}
var id = request.query.snuid;
var currency = request.query.currency;
var mac_address = request.query.mac_address;
var display_multiplier = request.query.display_multiplier;
//
request.status(200);
});
When I load up the browser and enter in the url:
http://localhost:8000/test?snuid=1234¤cy=1000&mac_address=00-16-41-34-2C-A6&display_multiplier=1.0
Im not sure why I am getting this error!? Not sure, it should work based on the documentation and examples I have seen. Any help would be appreciated.
I think is because you want to use a middleware and not a route, so maybe your code can be write in this way:
var express = require('express');
var app = express();
app.use(function(err, request, response, next) {
if (error) {
request.status(403);
return next();
}
});
app.get("/test", function(request, response, next) {
response.set("Content-Type", "text/html; charset=UTF-8");
var id = request.query.snuid;
var currency = request.query.currency;
var mac_address = request.query.mac_address;
var display_multiplier = request.query.display_multiplier;
//
response.status(200).end();
});
// Listen on port 8000, IP defaults to 127.0.0.1
var server = app.listen(8000, function() {
console.log("node express app started at http://localhost:8000");
});`
Related
It seems my Node JS or Express is caching the results from MongoDB, this seems to be an advantage for some, but for me it is causing a problem. I don't want the json response to be cached. Please suggest how to stop this.
This is my Server.js if you notice I have used res.headers and app.disable methods to prevent caching.
// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8000; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var messageId = {};
// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.Promise = global.Promise;
mongoose.connection.on('error', function(e) {
console.log('Can not connect Error:>>',e);
process.exit();
});
mongoose.connection.once('open', function(d) {
console.log("Successfully connected to the database");
})
//app.use(express.static('./public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
next();
});
app.disable('view cache');
io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
//res.writeHead(200,{'content-type':'text/plain'});
// res.write("Sever On");
// res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
console.log('User Connected -- Server Online');
socket.on('message', function (msg,msgId) {
io.emit('message', "Hello");
console.log("message from client:", msg);
setInterval(function(){
io.emit("messageStatus",msgId);
},500)
});
});
app.use(require('./app/routes.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);
This is my Route.js
var express = require('express')
var app = module.exports = express.Router();
var UserProfile = require('./models/UserProfile');
app.get('/User', function (req, res) {
UserProfile.find({
EmailID: req.query.EmailID
}, function (err, profile) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
return res.json({
"success": false,
"msg": err
})
console.log(err);
}
res.status(200).send(profile)
});
});
This is my provider.js
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class ProfileProvider {
data : any
constructor(public http: Http,) {
}
// public getProfile(EmailID){
// console.log(this.http.get(CONFIG.apiUrl+'User?EmailID='+EmailID).map(response => response.json().result));
// return this.http.get(CONFIG.apiUrl+'User?EmailID='+EmailID).map(response => response.json().result);
// }
public getProfile(EmailID){
console.log("Provider,>>",EmailID)
if (this.data) {
return Promise.resolve(this.data); }
return new Promise(resolve => {
this.http.get('http://192.168.0.100:8000/User?EmailID='+EmailID)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
}
Now if run this (http://192.168.0.100:8000/User?EmailID=abc#abc.com) on my browser and if I change the email ID, i get different responses. But in the ionic app it some how gives me the same responses even after changing the parameters
And I am using AWS and my MongoDB is hosted there.
Your problem is in the provider. You are caching the results of the api call in the data property.
if (this.data) {
return Promise.resolve(this.data); }
Try always fetching the data:
public getProfile(EmailID){
return new Promise(resolve => {
this.http.get('http://192.168.0.100:8000/User?EmailID='+EmailID)
.map(res => res.json())
.subscribe(data => {
resolve(data);
});
});
}
The problem I'm having is, the content that I try to send in my post request to the server doesn't get sent, but the request works.
Here's the code for the client:
$("#searchBtn").click(function(e){
try{
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/search/searchRequest", true);
console.log(($("#searchedSymptoms").val())) // gets posted in the console correctly
xhttp.setRequestHeader("Content-type", "text/plain"); // doesn't work without it either
xhttp.send($("#searchedSymptoms").val());
//xhttp.send(JSON.stringify($("#searchedSymptoms").val())); // doesn't work either
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(xhttp.responseText); // gets the correct response from server
}
else{
console.log(xhttp.responseText);
}
};
}
catch(err){
console.log(err);
}
});
And here's the server-side code:
var express = require("express");
var router = express.Router();
router.post("/searchRequest", function(req, res, next){
console.log("must get the client request:");
console.log(req.body);
//console.log(JSON.stringify(req.body)); // doesn't work either
});
In the server, what get's outputed to the console is this:
{}
Any thoughts on what I'm doing wrong ?
You need to use a text body-parser, Express won't do it by default, here's an example, using pretty much the same server side code you are:
"use strict";
var express = require("express");
var router = express.Router();
var bodyParser = require("body-parser");
router.post("/searchRequest", function(req, res, next){
console.log("must get the client request:");
console.log("SearchRequest: " + req.body);
res.end('ok', 200);
});
var port = 8081;
var app = express();
app.use(bodyParser.text());
app.use(router);
app.listen(port);
console.log("Express listening on port " + port);
You can configure the way the text body parser operates exactly by using the guide here:
https://www.npmjs.com/package/body-parser#bodyparsertextoptions
I am trying to connect my Angular2 to my nodeJs server. I have an authentication form which makes a post request. And I would like to use node to handle the post request.
But so far I am unable to make my post request working. The console.log doesn't display anything.
What I am missing?
This is my server.js which points to the folder dist in which i made the build of angular.
const express = require('express');
const path = require('path');
const http = require('http');
var walker = require('node-sync-walker');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
var app = express();
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
walker.routeWalker(__dirname + '/server/routes', app);
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
This is my api.js
var users = [{username: "user", password: "password"}];
var router = require('express').Router();
module.exports = function(app) {
router.post('/api/authenticate',
function(req, res) {
console.log("print something");
let params = JSON.parse(req.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
res.sendStatus(200);
} else {
console.log("print something else");
return res.sendStatus(400)
}
//return;
});
}
You are configuring the route as '/api/api/authenticate'
You should remove '/api' from routes in api.js
Finally, it worked! I removed the api in /api/authenticate as #catalacs suggested. Then I changed how I import the module router from api.js to server.js.
server.js
var users = [{username: "test", password: "test"}];
var router = require('express').Router();
router.post('/authenticate',
function(req, res) {
console.log("print something");
let params = JSON.parse(req.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
res.sendStatus(200);
} else {
console.log("print something else");
return res.sendStatus(400)
}
//return;
});
module.exports = router;
And in my server.js, I commented out this line:
walker.routeWalker(__dirname + '/server/routes', router);
I'm new to nodejs and I'm trying to solve communication issue with external system.
There is a gateway to external system which can handle websocket requests on port 5000. In the example below, when you request homepage, the nodejs opens websocket connection, then on websocket open event it sends request and waits for response which is used for the HTTP response.
Do you know how to open websocket to external system only once and handle requests based on request id?
var ws = require('ws');
var express = require('express');
var async = require('async');
var uuid = require('node-uuid');
app = express();
app.get('/', function (req, res) {
var webSocket = new ws('ws://localhost:5000/');
async.series([
function (callback) {
webSocket.on('open', function () {
webSocket.send(JSON.stringify({query:'data query', requestid: uuid.v4()}));
callback(null, 'data query');
});
},
function (callback) {
webSocket.on('message', function (data, flags) {
callback(null, data);
})
}
], function (err, results) {
res.setHeader('content-type', 'text/javascript');
res.send(results[1]);
webSocket.terminate();
});
});
var server = app.listen(3000, function () {
var port = server.address().port
console.log('Listening at %s', port)
});
Thanks for the hints. I ended with the following solution which does what I expect:
var ws = require('ws');
var express = require('express');
var uuid = require('node-uuid');
var requests = {};
app = express();
var webSocket = new ws('ws://localhost:5000/');
webSocket.on('open', function () {
console.log('Connected!');
});
webSocket.on('message', function (data, flags) {
var json = JSON.parse(data);
console.log(json.requestId);
var res = requests[json.requestId];
res.setHeader('content-type', 'text/javascript');
res.send(json.data);
delete requests[json.requestId];
});
app.get('/', function (req, res) {
var rid = uuid.v4();
requests[rid] = res;
webSocket.send(JSON.stringify({query:'data query', requestId: rid}));
});
var server = app.listen(3000, function () {
var port = server.address().port
console.log('Listening at %s', port)
});
I'm trying to use docpad to handle the rendering in an express application but when attempting to access /contact the request just hangs seemingly indefinitely.
Here is my application:
var express = require('express');
var http = require('http');
var app = express();
var cons = require('consolidate');
var server = http.createServer(app).listen(process.env.PORT || 9778);
app.use(app.router);
// Add DocPad to our Application
var docpadInstanceConfiguration = {
// Give it our express application and http server
serverExpress: app,
serverHttp: server,
// Tell it not to load the standard middlewares (as we handled that above)
middlewareStandard: false
};
var docpadInstance = require('docpad').createInstance(docpadInstanceConfiguration, function(err){
if (err) return console.log(err.stack);
// Tell DocPad to perform a generation, extend our server with its routes, and watch for changes
docpadInstance.action('generate server watch', docpadInstanceConfiguration, function(err){
if (err) return console.log(err.stack);
});
});
app.get('/contact', function(req, res) {
req.templateData = {
weDidSomeCustomRendering: true
};
var d = docpadInstance.getFile({relativePath:'hello.html.md'});
docpadInstance.serveDocument({document: d, req: req, res: res}, function(){});
});
This is pretty much copied straight from the documentation but does not work. Any ideas?
The key is to pass next:
app.get('/contact', function(req, res, next) {
req.templateData = {
weDidSomeCustomRendering: true
};
var d = docpadInstance.getFileAtPath('pages/hello.html');
docpadInstance.serveDocument({document: d, req: req, res: res}, next);
});
https://github.com/bevry/docpad/issues/706