While I was testing a weird behaviour in cache handling with Chrome (I asked something about it here), I found something else: Chrome dev tool shows a 200 status code when the server returns a 304 response.
Here you can see what chrome dev tool says (200) and I included a wireshark capture that shows the server 304 response.
Here is the same usage with Firefox, which shows the 304 code :
More interesting is the timing difference between the two browsers :
Firefox doesn't shows delay for the reception part but Chrome says it took 3.91ms.
Do you have any idea on why Chrome doesn't shows the right status code?
If you want to test yourself, here is the server code:
#!/usr/bin/env node
'use strict';
const express = require('express');
const cors = require('cors');
const compression = require('compression');
const pathUtils = require('path');
const fs = require('fs');
const http = require('http');
let app = express();
app.disable('x-powered-by');
app.use(express.json({ limit: '50mb' }));
app.use(cors());
app.use(compression({}));
app.use(function (req, res, next) {
res.set('Cache-control', 'no-cache');
console.log(req.headers);
next();
});
let server = http.createServer(app);
app.get('/api/test', (req, res) => {
res.status(200).send(fs.readFileSync(pathUtils.join(__dirname, 'dummy.txt')));
});
server.listen(1234);
and the client :
<!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>
<script>
let test = fetch('http://localhost:1234/api/test').then((res) => {
console.log(res.status);
return res.text();
});
</script>
</body>
</html>
I think that's actually a chrome bug. A bug report has been opened here : https://bugs.chromium.org/p/chromium/issues/detail?id=1269602
Related
I am following this video: https://youtu.be/5TxF9PQaq4U?t=600
When he makes a GET request to localhost:8383/info the JSON {info: "Text"} is shown inside the network-tab but the browser still displays the HTML page. When I make the GET request to localhost:8383/info, the browser displays the JSON but not the HTML. How can I get the same result as him?
Index.html (inside "public" folder)
<!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>
<form action="">
<input id="input" type="text">
<button id="get">Get</button>
</form>
</body>
<script>
const input = document.getElementById("input")
const getbtn = document.getElementById("get")
getbtn.addEventListener("click", getInfo);
async function getInfo(e) {
e.preventDefault()
const res = await fetch("http://localhost:8383/info", {method: "GET"})
console.log(res)
}
</script>
</html>
Server.js
const express = require("express")
const app = express()
const port = 8383
app.use(express.static("public"))
app.get("/info", (req, res) => {
res.status(200).json({info: "Text"})
})
app.listen(port, ( ) => console.log("Server started"))
This is what the browser displays on localhost:8383/info
I have tried to make the GET request to localhost:8383 (without info) but then the response is the HTML file, not {info: "Text"}.
You missed two places
#1 Need to add CORS in server.js
app.use(cors());
#2 Need to add DOM element in index.html and update it in script.
<p id="message">
The message will go here
</p>
...
document.getElementById('message').textContent = JSON.stringify(info);
This is full code.
const express = require("express")
const cors = require('cors');
const app = express()
const port = 8383
app.use(cors());
app.get("/info", (req, res) => {
res.status(200).json({info: "Text"})
})
app.listen(port, ( ) => console.log("Server started"))
<!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>
<form action="">
<input id="input" type="text">
<button id="get">Get</button>
</form>
<p id="message">
The message will go here
</p>
</body>
<script>
const input = document.getElementById("input")
const getbtn = document.getElementById("get")
getbtn.addEventListener("click", getInfo);
async function getInfo() {
const response = await fetch('http://localhost:8383/info');
return await response.json();
}
getInfo().then(info => {
document.getElementById('message').textContent = JSON.stringify(info);
});
</script>
</html>
Result - ran GO Live extension in VS.code and node server.js
Im trying to create simple node.js server for html using http and express
It's working, but css don't showing
Here is code of my server
const express = require("express");
const app = express();
app.use(express.static("css"));
var router = express.Router()
app.use('/',router)
router.get("/", (req, res) => {
res.sendFile(__dirname + "/index.htm")
})
app.listen(8080)
And code of my server, what created using http
const http = require("http")
const port = 8080
const fs = require('fs')
const server = http.createServer(function(req,res) {
fs.readFile('./index.html', (error, data) => {
if(error) {
res.writeHead("404")
res.write("Error. File not found.")
} else {
res.use
res.write(data)
}
res.end();
})
})
server.listen(port, function(error) {
if(error) {
console.log(error)
} else {
console.log("server is listening on port " + port)
}
})
all my html code
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Domodinak</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<p>Hello world</p>
</body>
</html>
also css
body {
background-color: deeppink;
}
if you know how to help me, please help :)
Make sure that you're addressing css folder correctly. It depends on your project folder structure. It is suggested to save your static files in a folder called public and then save your files in separated folder like js and css. For example, i assume that you have a src folder which is your directory for express server file, another folder alongside the src folder, you have a public folder with css subfolder.
Put your stylesheet file in css subfolder, and html file in just public folder and then change your code to this:
const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname, "../public")));
// var router = express.Router()
// app.use('/',router)
// router.get("/", (req, res) => {
// res.sendFile(__dirname + "/index.htm")
// })
app.listen(8080)
Your project structure should looks like this:
|-public -| css -| style.css
index.html
|-src -| app.js
Run the server file then check your browser with just localhost:8080. It serves index.html from static directory which you passed to express earlier.
var express = require('express');
var app = express();
app.use("/", function(request, response){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Test");
dbo.collection("users").find({}, { "name":"John" }).toArray(function(err, result) {
if (err) throw err;
console.log(result);
// res.sendFile(__dirname + "/views/index.ejs");
db.close();
});
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="./index.js"></script>
<title>Document</title>
</head>
<body>
<h1 id="result"><%=result%></h1>
</body>
</html>
I have 2 files and I want to use a variable from one file in another. How can I send the variable result from my nodejs file to my ejs file, in <h1 id="result"><%=result%></h1>?
In order to do that you have to use express res.render()
according to the docs
res.render(view [, locals] [, callback])
Renders a view and sends the rendered HTML string to the client. Optional parameters:
locals, an object whose properties define local variables for the view.
You should use something like this
res.render('index',{result});
then now you would be able to access that value you have sent over in your index.ejs file however I would advice you to explicitly declare in your application that you are using ejs so that you would not have to go through the struggles of re-stating ejs at the end of you code like before
at the top after this code var app = express()
you could say
app.set("view engine", "ejs");
I'm getting the message "Failed to load resource: the server responded with a status of 404 (Not Found)" on my css file. My site is a node app hosted on a Digital Ocean server
const express = require('express');
const app = express();
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
body {
background-color: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Brand Central Network</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>www.brandcentralnetwork.tv</h1>
</body>
</html>
I am using Angular6, trying to serve json data from a google map API to make ajax calls to Node.js with MongoDB, I have a form for placing markers on a google map using the api, I am trying to set up node js to take in the json data so that it is not being stored on the local storage, I have being following tutorials trying to set up Node.js to work with express and to store the places.
Using express: "^4.16.3", mongodb: "^3.1.1",
I have created the dist folder with all of the relevant files and I have also created my server folder with route folder and api.js, also I have my server.js, I think that I have all in place but I keep getting this error in my console when I run it on the local host 3000,
this is the error that is showing up in my google chrome console
When I run http://localhost:3000/api it displays that the text 'api works'
This is my Server.js
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
// Get our API routes
const api = require('./server/routes/api');
const 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/mapit/index.html'));
});
/**
* 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
const express = require('express');
const router = express.Router();
/* GET api listing. */
router.get('/', (req, res) => {
res.send('api works');
});
module.exports = router;
This is my index.html in my dist folder
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mapit</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://bootswatch.com/4/simplex/bootstrap.min.css">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="runtime.js">
</script><script type="text/javascript" src="polyfills.js"></script>
<script type="text/javascript" src="styles.js"></script>
<script type="text/javascript" src="vendor.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
I think you have the following problem, you don't call next on your middleware and thus the HTML file cannot be send. You also try to call res.send() twice which you shouldn't do, express can only send one response. I suggest you change your api the following:
router.get('/', (req, res, next) => {
console.log('api works');
next();
});
Now the api works will logged in the terminal (nodejs) and not the browser console and the HTML should be send succesful.
Hopefully helps you!
Try app.use(express.static(path.join(__dirname, 'dist/mapit')));
Difference is using 'dist/mapit' instead of only 'dist'.
Where have you placed your server.js file? I was seeing the same issue when I had my server.js within the DIST folder.
I moved the server.js file up one level so it is in the parent directory of the DIST folder and my site files css/js etc all loaded as expected.