How do I get emoticons working in express? [duplicate] - javascript

I am trying to create a POST with an emoji to my Express endpoint:
curl --data '{"x": 10, "y":10, "z":10, "message": "😋", "userToken": "Marine"}' --header "Content-Type:application/json" localhost:3000/api/messages
For some reason this crashes my server:
SyntaxError: Unexpected token
at Object.parse (native)
at parse (/Users/user/Documents/uncovery/node_modules/body-parser/lib/types/json.js:84:17)
at /Users/user/Documents/uncovery/node_modules/body-parser/lib/read.js:102:18
at IncomingMessage.onEnd (/Users/user/Documents/uncovery/node_modules/body-parser/node_modules/raw-body/index.js:149:7)
at IncomingMessage.g (events.js:199:16)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
I went to my router and put console.log's in my /messages endpoint to see what is being received but when Express crashes as a result of sending an emoji the console.log is never activated.
router.js
var models = require('../db/models.js');
var util = require('../core/utilities.js');
var sockets = require('../routes/sockets.js');
module.exports = function(router) {
//input: {x: float, y: float, z: float, message: string, userToken: string}
router.post('/messages', function(req, res) {
console.log("Emoji: ", req.body);
models.createMessage(req.body).then(
util.resolvePOST.bind(this, req, res),
util.rejectPOST.bind(this, req, res)
);
});
}
I suspect this has something to do with the middleware and not actually related to the routes, but when I google emojis crash node js I can't find anything relevant. Why is this happening?
index.js
var http = require('http');
var morgan = require('morgan');
var express = require('express');
var socketIO = require('socket.io');
var bodyParser = require('body-parser');
var util = require('./server/core/utilities.js');
var router = require('./server/routes/router.js');
var sockets = require('./server/routes/sockets.js');
var app = express();
var server = http.Server(app);
app.use(morgan('combined', util.getLogStream()));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '50mb' }));
app.use('/api', router);
app.use(express.static(__dirname + '/server/landing'));
var io = socketIO(server);
sockets.initialize(io);
server.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Uncovery listening at http://%s:%s', host, port);
});

Related

Node.js and Express relationship

I'm trying to understand the connection between Node.js and Express.
My Code for creating a Node.js Server:
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, function(req,res){
res.writeHead(200);
res.end(`Hello world!!!!!!!!!!! \n`);
});
server.listen(3000, function(){
console.log('Server listening on port 3000 \n');
});
I run a curl operation curl -k localhost:3000 and it gives me a "Hello World" Output
My code for creating an Express Server:
// call the packages we need
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
// ROUTES FOR OUR API
var router = express.Router();
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
app.listen(port);
console.log('Magic happens on port ' + port);
Is it possible for us to mix both of these?
To be more specific, I would like to create my Server using the Node.js way, but create my routes using the Express way. Can I do it or should I just follow one methodology? What is the connection between Node.js and Express? I understand that Express is just a framework for Node.js but where exactly does the deviation occurs if at all any?
Can I mix and combine the two when required?
Thank you
Yes you can combine nodejs and express, but not encourage you to combine those unless you have specific purpose such as using AWS lambda or making specific OS tasks that has to be made only with pure node.
As you already know, express is just a framework. You can write code more shortly using express.
For example, to make the browser displaying Hello world,
// nodejs version
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// express version
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, (req, res) => {
res.send('Hello World!\n');
})
More easier, and intuitive.
You surely can that's the way to create a Secure HTTPS server with express and followed in most projects
const https = require('https');
const express = require('express');
const app = express();
const options = {
key: fs.readFileSync('./https1/key.pem'),
cert: fs.readFileSync('./https1/cert.pem')
};
const server = https.createServer(options, app);
app.get('/', (req, res) => {
res.send('hello world')
}
server.listen(config.port, () => {
console.log(`Express server listening on port ${port} in ${app.get('env')} mode`);
});
Now add your routes and all.

NodeJS res.body is undefined only on one router

I am sending data using swift to a nodeJS server.
Here is the Swift Code:
var data:[String:String] = [:]
data["ABC"] = "nothing"
let req = HTTPRequest(url_to_request: "https://xxx.xxx.xx.x/update", method: HTTPRequest.HTTPRequestMethod.post, data: Profile.toJSON(dict: data))
Here is the NodeJS:
console.log("Server is up!");
var bodyParser = require('body-parser');
var express = require('express');
var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var http = require('http');
var https = require('https');
var fs = require('fs');
var bcrypt = require('bcryptjs');
var sslOptions = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('cert.pem', 'utf8'),
passphrase: 'phrase',
rejectUnauthorized: false
};
var app = express();
//Variables:
var httpPort = 8888;
var httpsPort = 8443;
app.use(bodyParser.urlencoded({
extended: false,
limit: '20mb'
}));
app.use(bodyParser.json({
limit: '50mb'
}));
// parse application/json json size limit
// parse application/x-www-form-urlencoded
// setup server
app.set("port_https", httpsPort);
//check secure connection
app.all("*", function(req, res, next) {
console.log("Secure connection: " + req.secure);
if (req.secure) {
return next();
}
res.redirect("https://" + req.hostname + ":" + app.get("port_https") + req.url);
});
// add User
app.post('/register', register);
//signIn
app.post('/login', logIn);
//Update user's profile details.
app.post('/update', updateProfile);
// Request profile details.
app.post('/profile', profileRequest);
function updateProfile(req, res) {
console.log(res.body); // ---> undefined
}
When I send a post request with data to login, profile, register routers res.body is working well. But when I send data to update for some reason req.body is undefined:
ERROR:
Server: Secure connection: true
Server: undefined #----> log of res.body
Server: Connected successfully to databse!
stderr: /home/asaf/NodeJS/IBQA/IBQA_Server/node_modules/mongodb/lib/mongo_client.js:350
throw err
^
TypeError: Cannot read property 'ABC' of undefined
at /*****/server.js:92:33
at connectCallback (*****/mongo_client.js:428:5)
at /*****/node_modules/mongodb/lib/mongo_client.js:347:11
at nextTickCallbackWith0Args (node.js:419:9)
at process._tickCallback (node.js:348:13)
closing code: 1
Your request if there in the req variable, res is used to send the response. Try console.log(req.body)

Express Post Request 404

I'll try to make this as to the point as possible. I am trying to make a post request to my express backend. All of the post requests here work, except for "/addpayment". Here is my file called 'router.js'
module.exports = function(app) {
app.post('/signin', requireSignin, Authentication.signin)
app.post('/signup', Authentication.signup)
app.post('/addpayment', function(req, res, next) {
res.send({ message: 'why................' })
})
}
Here is my main 'server.js' file
const express = require('express')
const http = require('http')
const bodyParser = require('body-parser')
const morgan = require('morgan')
const app = express()
const router = require('./router')
const mongoose = require('mongoose')
const cors = require('cors')
// DB Connect
mongoose.connect('mongodb://localhost/demo-app')
// App
app.use(morgan('combined'))
app.use(cors())
app.use(bodyParser.json({ type: '*/*' }))
router(app)
// Server
const port = process.env.PORT || 3090
const server = http.createServer(app)
server.listen(port)
console.log('Server has been started, and is listening on port: ' + port)
I get a 404 in postman, and inside my app browser console. I am using passport in my other routes. I already tried running it through passport when I have a JWT token, and same thing(a 404).
I have already looked at all Stack Overflow/Github posts on the first few pages of google results, with no solution for my use case.
I have made a simplified version of your server and everything works as expected. Only difference that I have made is that I am not creating http server like you, but just calling app.listen
here is working example
router.js
module.exports = function(app) {
app.post('/addpayment', function(req, res, next) {
res.send({message: 'why................'})
})
};
server.js
var express = require('express');
var router = require('./router');
var app = express();
router(app);
//init server
app.listen(3000, function() {
console.log("Server running on port 3000");
});

javascript node.js Server with html

I have a Problem with my Node.js Server. I want to host a html Document but there is one Problem with a TypeError. I cann't find the mistake. Can you help me?
var express = require("express");
var mysql = require('mysql');
var app = express();
var fs = require("fs");
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : '',
database : 'test',
debug : false
});
app.get('/', function(req, res) {
fs.readFile('index.html', 'utf-8',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
});
});
app.listen(3000);
console.log("SERVER IS NOW RUNNING AT PORT 3000........");
Here now the log:
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.2\bin\runnerw.exe" "C:\Program Files\nodejs\node.exe" Server.js
SERVER IS NOW RUNNING AT PORT 3000........
_http_outgoing.js:430
throw new TypeError('first argument must be a string or Buffer');
^
TypeError: first argument must be a string or Buffer
at ServerResponse.OutgoingMessage.write (_http_outgoing.js:430:11)
at ReadFileContext.callback (c:\........\Server.js:21:13)
at FSReqWrap.readFileAfterOpen [as oncomplete] (fs.js:303:13)
Later I want to make a MySQL Connection with Pooling.
You can also use createReadStream and .pipe to res but as #robertklep mentioned, you should check if (err) inside the readFile callback.
Here is the example
var fs = require('fs');
var http = require('http');
var file = fs.createReadStream('/path/to/file');
var server = http.createServer(function (req, res) {
// res.writeHead(200, {
// 'content-type': 'text/plain'
// });
file.pipe(res);
});
server.listen('3000');
UPDATE
So to match your code using express, you don't have to do much:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(3000, function () {
console.log('SERVER IS NOW RUNNING AT PORT 3000........');
});
Just put all your assets in the public folder and you should be good to go. To find more info about Express you can go to http://expressjs.com/en/4x/api.html

Listen on HTTP and HTTPS for a single express app

Can I create an Express server listening on both HTTP and HTTPS, with the same routes and the same middlewares?
Currently I do this with Express on HTTP, with stunnel tunneling HTTPS to Express, but I prefer a pure Node solution.
I can do it with this code, but using the handle method that is marked as private:
var express = require( 'express' )
, https = require("https")
, fs = require( 'fs' );
var app = express.createServer();
// init routes and middlewares
app.listen( 80 );
var privateKey = fs.readFileSync( 'privatekey.pem' ).toString();
var certificate = fs.readFileSync( 'certificate.pem' ).toString();
var options = {key: privateKey, cert: certificate};
https.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen( 443 );
To enable your app to listen for both http and https on ports 80 and 443 respectively, do the following
Create an express app:
var express = require('express');
var app = express();
The app returned by express() is a JavaScript function. It can be be passed to Node’s HTTP servers as a callback to handle requests. This makes it easy to provide both HTTP and HTTPS versions of your app using the same code base.
You can do so as follows:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem'),
ca: fs.readFileSync('/path/to/ca.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
For complete detail see the doc
As a possible update to this question, you might want to check out the changes here for express 3. The change document says:
The return value of express() is a JavaScript Function,
encapsulating everything that makes an Express app tick. This means
you can easily setup HTTP and HTTPS versions of your application by
passing it to node's http.createServer() and https.createServer():
In Express 3, express.createServer() is now express()
Here is a complete example for express 3:
var fs = require('fs')
, https = require('https')
, http = require('http')
, express = require('express')
, keys_dir = 'keys/'
, server_options = {
key : fs.readFileSync(keys_dir + 'privatekey.pem'),
ca : fs.readFileSync(keys_dir + 'certauthority.pem'),
cert : fs.readFileSync(keys_dir + 'certificate.pem')
}
, app = express();
app.configure(function(){
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session( { secret: '' } ));
app.use(app.router);
});
app.configure('development',function(){
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({dumpExceptions: true, showStack:true}));
app.set('view options', { pretty: true });
});
app.get('/', function(req, res){
res.send('Hello World!');
});
https.createServer(server_options,app).listen(7000);
http.createServer(app).listen(8000);
You can share the implementation via something like:
var register = function (app) {
// config middleware
app.configure({
});
// config routes
app.get(...);
};
var http = express.createServer();
register(http);
http.listen(80);
var https = express.createServer({ key: /* https properties */ });
register(https);
https.listen(443);
You can use express and https in same port.
this works for me.
const express=require('express');
const app=express();
const cors=require('cors');
const path=require("path");
const routes=require('./routes/api');
const routerComplain=require('./routes/api');
const routerstores=require('./routes/api');
const routerstock=require('./routes/api');
const routerreport=require('./routes/api');
const routeritem=require('./routes/api');
const bodyParser=require('body-parser');
const routerRegister=require('./routes/api');
const mongoose=require('mongoose');
var server = require('http').Server(app);
var io = require('socket.io')(server);
require("dotenv").config();
mongoose.connect('mongodb://#################',{ useNewUrlParser: true },(err)=>{
if(!err){
console.log('db connected')
}else{
console.log('error in db')
}
});
mongoose.Promise = global.Promise;
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(cors({credentials: true, origin:'http://localhost:3000'}));
app.use(express.static(path.join(__dirname, "client", "build")))
app.use('/reg',routes);
app.use('/complain',routerComplain);
app.use('/register',routerRegister);
app.use('/stores',routerstores);
app.use('/reports',routerreport);
app.use('/stock',routerstock);
app.use('/items',routeritem);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
})
const port = process.env.port||4000;
server.listen(port,function(){
console.log('now listening for request');
});
If you want to use the traditional two ports, one of the above solutions probably works, but using httpolyglot, you can really easily have http and https on the same port with the same middlewares.
https://github.com/mscdex/httpolyglot
Here's some skeleton code that worked for me:
var express = require('express');
var fs = require('fs');
var httpolyglot = require('httpolyglot');
var app = express();
const options = {
key: fs.readFileSync("/etc/ssl/certs/key"),
cert: fs.readFileSync("/etc/ssl/certs/cer.cer")
};
httpolyglot.createServer(options, app).listen(port);
and if you want http -> https forwarding, you can just add this middleware function before the createServer() call:
app.use(function(req, res, next) {
if (!req.secure ) {
res.redirect (301, 'https://' + req.hostname + ':port' + req.originalUrl);
}
next();
});
This can be set up on a custom port
Similar post
Can I configure expressjs to serve some pages over http and others over https?
Be aware that express now support creating Https servers with:
var app = require('express').createServer({ key: ... });

Categories

Resources