I'm trying to send two responses for a javascript file and a html file but the client isn't receiving either. Why is the client not receiving the html and javascript files? I'm using Nodejs, javascript, and html.
server.js:
const http = require('http');
const fs = require('fs');
const hostname = '127.0.0.1';
const port = 3000;
// use createReadStream instead to save memory
const index = fs.readFileSync('www/index.html');
const java = fs.readFileSync('javascript.js');
// this is our request handler
const server = http.createServer((req, res) => {
res.statusCode = 200;
//res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Type', 'text/html');
res.end(index);
res.setHeader('Content-Type', 'text/html');
res.end(java);
//res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
index.html
<!DOCTYPE html>
<script src="javascript.js"></script>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button" onclick='changeme()'>Click Me!</button>
</body>
</html>
javascript.js
function changeme() {
document.getElementById("demo").innerHTML = "Hello JavaScript!"
}
Did you try specifying that it's in the same directory as your server.js file, ie
const java = fs.readFileSync('./javascript.js');
It seems that there's a problem finding the file, this link should help you with this issue. I hope this helps you.
try out
const fs = require("fs");
const hostname = "127.0.0.1";
const port = 3000;
// use createReadStream instead to save memory
const index = fs.readFileSync("index.html");
const java = fs.readFileSync("javascript.js");
// this is our request handler
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.setHeader("Content-Type", "text/html");
res.write(index);
}
if (req.url === "/javascript.js") {
res.setHeader("Content-Type", "text/javascript");
res.write(java);
}
res.statusCode = 200;
// res.writeHead(200, java);
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.