Node.js express: why can't I read cookies ? - node.js

I wrote a very simple node.js server:
var express = require('express');
var cookieParser = require("cookie-parser");
var app = express();
app.use(cookieParser());
app.get('/', function(req, res){
res.sendFile(__dirname + "/hello.html");
});
app.get('/ajax', function(req, res) {
console.log('ajax request received');
console.log(req.cookies["username"])
})
app.listen(3000);
and a very simple client side html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> Hello World </h1>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
document.cookie = "username=John Doe";
$.ajax({
url: "http://127.0.0.1:3000/ajax",
}).done(function() {
alert('AJAX sent');
});
</script>
</body>
</html>
As you can understand, once the server runs and an end-user sends a get request to localhost:3000, the file 'hello.html' is served to client. The browser saves the cookie "username=John Doe" and sends AJAX request to endpoint localhost:3000/ajax. My intention is to read the content of the cookie in the server (I know that cookies are sent automatically from the client). However, req.cookies["username"] returns undefined.
Do you know why?

The problem is that I send a GET request to localhost:3000 and therefore the cookie is saved in the domain http://localhost. However, when I send an AJAX call to 127.0.0.1, the cookie is not sent because the browser treats 127.0.0.1 and localhost as different domains. Therefore, opening the browser with 127.0.0.1:3000 (instead of localhost:3000) can solve it.

Related

Serve multiple type files on pure node.js

I have a simple pure node.js server which sends back html page on request.
In my html page i have connected js file.
When i make a request i get on response the html page but no the js file.
In my console i got an error.
Uncaught SyntaxError: Unexpected token '<'
my node.js server file:
const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html', });
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
console.log('Server is running on Port: 8080');
my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>here</h1>
<script src="./app.js"></script>
</body>
</html>
Any suggestions how to send multiple files on request with pure js ?
You're currently serving all requests with index.html, so when the browser requests app.js you do not get the script, but the index-page instead, hence the error.
You'd need to check the request path in your server's callback and then send the correct file (see this for a more detailed example):
http.createServer(function (req, res) {
if (req.path === '/app.js') {
// read app.js file and send it to the client
} else {
res.writeHead(200, {'Content-Type': 'text/html', });
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
You see that this is pretty cumbersome, so I highly recommend using a framework like express (it provides a middleware to serve static files out of the box) to do this.

POST request not working in NodeJs app in Cpanel

I was creating a Node App using Express JS. There's a route which accepts a POST Request. The app works fine on localhost, but when I host on Cpanel Shared Hosting, I get the following error for POST request. GET works fine. Can anyone please help or guide where I went wrong?
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /v1/email</pre>
</body>
</html>
My Express JS code
var app = express();
var em =require('./mailjet')
var bodyParser = require('body-parser');
app.use(bodyParser.json())
app.get('/v1', function (req, res) {
return res.json('Hello World');
})
app.post('/v1/email', function (req, res) {
let {name, email, message}=req.body
if (!name || !email || !message){
return res.status(400).send({
'Message':'Bad Request'
})
}
em.request(name, email, message)
return res.status(200).send({
'Message':'Email Sent'
});
})
app.listen()

Cannot Get in Node Js

I am new to node js and creating a simple application to query data stored in database(MySql) .So what i am doing is, I have created a database named stock and i am querying it using index.html to show it at get.html but after executing the get request i am not able to get the result.
Here is my app.js
const express=require('express');
const app=express();
const port= 5050;
const bodyParser=require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',(req,res)=>res.sendFile(__dirname + '/index.html'));
app.post('/get',function(req,res){
const mysql=require('mysql');
const con=mysql.createConnection({
host:"localhost",
user:"root",
password:"abc123",
database:"abc",
});
con.connect(function(err){
if(err) throw err;
console.log("Connected");
let sqlQuery='SELECT * FROM stock';
con.query(sqlQuery,(err,rows)=>{
if(err) throw err;
console.log('Data Received:-');
console.log(rows);
});
});
});
app.listen(port);
My Index.html:-
<!DOCTYPE html>
<html>
<head>
<title>My node js app</title>
</head>
<body>
<form action="/get" method="get">
<h1>Welcome to Stock manipulation</h1><br></br>
Select option<select>
<option value=0>Get</option></select>
<input type="submit" id="query" value="get Result">
</body>
</html>
And my get.html
<!DOCTYPE html>
<html>
<head>
<title>Get</title>
</head>
<body>
</body>
</html>
And here is the data stored at database
[ RowDataPacket { id: 1, type: 'BSE' },
RowDataPacket { id: 2, type: 'NSE' } ]
The error i am getting after Submitting the request is
What is your nodejs server saying? In your routes you typically want to return some data. for example in your case your /get route res.send(data). that way your front end can show the data received. Also looks like you need to change your form to be a post not a get (Edit: As Nikos M. mentioned).
If you are new to http requests I recommend downloading Postman to get used to testing your routes requests.
change
<form action="/get" method="get">
to
<form action="/get" method="post">
as you have defined the /get route (app.post('/get',function(req,res){/*..*/}))
to accept only post requests
Also in your /get route handler you should output something. Right now you do not output anything, only log to the node.js console

Express.js + HTML5 appcache not working in Firefox

I want to use HTML5 app cache in my MEAN app but I can't make it work in Firefox 36. It works in Chromium as expected. This is my file structure:
client
app.js
manifest.appcache
views/
index.html
about.html
server.js
index.html:
<!DOCTYPE html>
<html manifest="/manifest.appcache">
<head>
<meta charset="UTF-8">
</head>
<body>
About
</body>
</html>
manifest.appcache:
CACHE MANIFEST
#0
CACHE:
views/about.html
app.js
server.js:
var http = require("http");
var express = require("express");
var app = express();
app.get("/manifest.appcache", function (req, res) {
res.set("Content-Type", "text/cache-manifest");
res.set("Cache-Control", "no-store, no-cache");
res.set("Expires", "-1");
res.sendFile("/client/manifest.appcache", {root: __dirname});
});
app.get('/', function (req, res) {
res.sendFile('/client/views/index.html', {root: __dirname});
});
app.use(express.static(__dirname + '/client', { maxAge: 31557600000 }));
app.listen(8080);
When I go to localhost:8080, Firefox successfully fetches the manifest (which is not visible in the network tab of dev tools) but it does not store the files in the app cache (Preferences - Advanced - Network shows 0 bytes). It loads them from the standard system cache (I get 304).
I suspect that my routing somehow breaks the links in manifest.appcache but I had to prevent the manifest to be cached itself. I'm not an expert on Node.js and I'm confused by the fact that Chromium and Firefox behave differently. Any help will be appreciated.

Working with node js and angular js

I am just trying out node js and angular js. here is my node code:
var http = require('http');
var fs = require('fs');
var sys = require('sys');
http.createServer(function(req, res){
fs.readFile('angularjsex.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
}).listen(8000);
The angularjsex.html file:
<html ng-app>
<head>
<script type="text/javascript" src="angular.js"></script>
</head>
<body>
<div>
<label>Name:</label>
<input type="text" ng-model="yourName" placeholder="Enter a name here">
<hr>
<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>
The angular js just does not work. Am i missing something?
You are returning the contents of the file angularjsex.html for every request. In your HTML file, there's a reference to angular.js that the browser will try to load from your server, and that request will get the same (HTML!) contents.
For a solution that works with your current server app, replace this:
<script type="text/javascript" src="angular.js"></script>
With this:
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
But I would suggest to start using Express, in which case you can leave the HTML code as is if you change your server to this:
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8000);
Create a directory public and place your angularjsex.html and angular.js files into it. To view the result, open http://localhost:8000/angularjsex.html in your browser.
To install Express:
npm install express

Resources