Node.js & Express.js Font Differentiation - javascript

I developed examples on Node.js and Express.js arbtrarily. After initiating example.js of each one shown below, I ran into a font differentiation between them. Even I know Express is a framework for Node, I couldn't find anywhere why typography change though.
Node.js:
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.js:
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Output For Node.js:
Output For Express.js:

and here is Express.js version handles the same job
Well, no, not entirely. Your "plain Node" example explicitly sets the content-type to "text/plain", but you don't do the same for the Express example, in which case it will default to "text/html".
If the server tells the browser that the response contains HTML, the browser will apply a default CSS stylesheet, which usually includes a body font (something like Times New Roman).
When you use "text/plain", most browsers will render the content in a monospaced font.

Related

How should I use proxy in a web app made with node.js and vanilla javascript?

I have a web app made in node.js and vanilla javascript. I wanna replace "http://localhost:4000/api/word" with "api/word" in the fetch api so that it works when the app's deployed on Heroku. I solved the issue by adding "proxy" : "http://localhost:4000" in package.json file when I used React for other apps but I don't know how to deal with the issue when I'm not using React.
server.js
const express = require("express");
const app = express();
const cors = require("cors");
const fs = require("fs");
const port = process.env.PORT || 4000;
app.use(express.json());
app.use(cors());
app.get("http://localhost:4000/api/word", function (req, res) {
fs.readFile("./wordlist.txt", (err, data) => {
if (err) throw err;
let wordList = data.toString().split("\n");
res.send(wordList);
});
});
main.js
function getWord() {
fetch("/api/word")
.then((res) => res.json())
.then((res) => {
...do something...
})
.catch((err) => console.log(err));
}
I tried the React way but it sends the get request to localhost:5500 which is the client side port.
Since your client and server are listening on different ports, I'm assuming your server isn't serving the client and that it has its own server. If the client doesn't need its own separate server, you can serve it from your express app by putting it in a directory and using express.static. Assuming you put the frontend code in a directory called public next to your server code, that would look like this:
app.use(express.json());
app.use(cors());
app.use(express.static(path.resolve(__dirname, 'public')));
If you do need to have a separate server for the client, there are modules just for this problem. http-proxy is a very popular one. I provided examples of how to use it here that could be easily adapted for any Node server, but there are many more in the docs.
Also just a sidenote, app.get("http://localhost:4000/api/word", function (req, res) should be app.get('/api/word' ...: your routes shouldn't define the scheme, host, and port.

Styling an html page in a node.js application

I have just tried to build up a server on localhost to display an html page. All good so far. The problem arises when I try to style my html page with a css file.
Consider that all my file are in the same directory.
If I run node app.js and I go to local host I can see the page but with no css styling…could you please help me?
Thanks
App.js
const http = require('http');
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, '/')));
let {requestListener} = require('./callbackFile.js');
const PORT = process.env.PORT || 4001;
const server = http.createServer(requestListener);
server.listen(PORT);
console.log("");
console.log("express server should be up&running. Please go to http://localhost:"+PORT);
callbackFile.js
const fs = require('fs');
module.exports = {
requestListener: (req, res) => {
fs.readFile('./ws.html', 'utf-8', (err, data) => {
if (err){
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(`${err}`);
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
})
}
}
ws.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title> website page </title>
</head>
<body>
<h1> Web server up & Running </h1>
<h4> Express Server listening on port 4001 </h4>
</body>
</html>
style.css
h1 {
color: "red";
{
The problem here is that you set up your http server to respond to every request with ws.html. I think it will be clearer if I show a solution you instead of telling you.
App.js
const PORT = process.env.PORT || 4001;
const http = require('http');
var express = require('express');
var path = require('path');
var app = express();
let { requestListener } = require('./callbackFile.js');
app.get("/", requestListener);
app.use(express.static(path.join(__dirname, '/')));
const server = http.createServer(app);
server.listen(PORT);
console.log("");
console.log("express server should be up&running. Please go to http://localhost:"+PORT);
style.css
h1 {
color: red;
}
What I am doing here:
Instead of passing the function requestListener to the http.createServer() function, I passed in the express app variable. You will see the reason for this later.
I put the requestListener function in an Express route. What that does is route all requests for the url "/" to the requestListener function. All other routes will be routed to the Express middleware below that.
I removed the quotes from the h1 styling in the style.css file. As #Phix said, CSS colours don't use quotes.
Why this works
As said in the Express 4.x documentation:
The app returned by express() is in fact a JavaScript Function, designed to 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 with the same code base, as the app does not inherit from these (it is simply a callback):
var express = require('express')
var https = require('https')
var http = require('http')
var app = express()
http.createServer(app).listen(80)
https.createServer(options, app).listen(443)
So, I guess you could say that an Express application is basically a convenient way of defining a callback function for a http or https server
Here is the express 4.x documentation if you need it.
https://expressjs.com/en/4x/api.html
Hope this helps :)

How do i force express to serve static html documents having no file extentions with 'text/html' content type

I made a statically generated site with html files encoded as 'utf-8'
Served from express
they reside in a static directory
I discovered after omitting the file extension of my webpages before saving them
when opened in the browser the webpages were getting downloaded instead of getting rendered as html documents normally would
til now couldn't find any relevant information on the subject.
The static module accepts a setHeaders function which can dynamically add headers to any static file it serves.
You can test if the file hasn't got a file extension and add the header dynamically:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('Hello World!'))
// This is a bit quick and dirty, but should be suitable for most cases
const noFileExtension = /[^.]{5}$/;
const staticOptions = {
setHeaders: (res, path, stat) => {
if (path.match(noFileExtension)) {
res.set('Content-Type', "text/html");
}
}
}
app.use(express.static('public', staticOptions));
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
A very hacky way to do it will be setting the headers in the static options. Now you can add if clauses that say if the path doesn't have extension etc etc. But basically this will work:
const express = require('express');
const app = express();
app.use(express.static(<your directory>, {
setHeaders: function (res, path, stat) {
res.set('Content-Type', 'text/html');
}
}))
app.listen(8080);

How to set React app and API on same port?

I've got a React app that via an API pulls data from a separate database.
When I run it locally, the app is one port and the API is on another port.
Since when I make AJAX calls in the app to the API, I need to include the URL where the API can connect.
It works if I hardcode the separate port (e.g., the app is on http://localhost:3000 and the API on http://localhost:3100, making the AJAX url call to the API http://localhost:3100/api/trusts).
However, since the app and API are on different ports, I can't make the AJAX url a relative path because it erroneously sends the AJAX call to http://localhost:3000/api/trusts and not http://localhost:3100/api/trusts.
How do I get them to run on the same port?
Thanks!
Here's my server.js:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//set our port to either a predetermined port number if you have set it up, or 3001
var port = process.env.PORT || 5656;
//db config
var mongoDB = 'mongodb://XXX:XXX!#XXX.mlab.com:XXX/XXX';
mongoose.connect(mongoDB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//body parsing
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// allow cross-browser
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
// handling static assets
app.use(express.static(path.join(__dirname, 'build')));
// api handling
var TrustsSchema = new Schema({
id: String,
name: String
});
var Trust = mongoose.model('Trust', TrustsSchema);
const trustRouter = express.Router();
trustRouter
.get('/', (req,res) => {
Trust.find(function(err, trusts) {
if (err) {
res.send(err);
}
res.json(trusts)
});
});
app.use('/api/trusts', trustRouter);
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!'});
});
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
Below is the AJAX call I'm trying to make that doesn't work because the relative path is appended to the app's port (i.e., http://localhost:3000/) and not the API's port (i.e., http://localhost:3100/):
axios.get("/api/trusts")
.then(res => {
this.setState({trusts: res.data});
})
.catch(console.error);
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:4000",
This way, when you fetch('/api/todos') in development, the development server will recognize that it’s not a static asset, and will proxy your request to http://localhost:4000/api/todos as a fallback. The development server will only attempt to send requests without text/html in its Accept header to the proxy.
"Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production."
Note: this feature is available with react-scripts#0.2.3 and higher.
More details here: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development

npm module or software which checks and tells what methods we have used for node js

I am working on a JS application which has a lot of NPM modules written in NodeJS and ReactJS. Since NodeJS is a big framework i'm not sure which NodeJS methods are used. Are there any NPM modules or software which checks and tells what methods we have used in our NodeJS code?
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}/`);
});

Categories