node.js cannot be moved from browser

Asked 2 years ago, Updated 2 years ago, 40 views

I would like to move JS as server side from browser, but the JS file to which the file is loaded is returned.When I was running PHP with Apache, I wrote the loading of the module for that in httpd.conf, but I thought it was necessary to set it up like that, so I looked it up, but there was no particular information, so I was at a loss.Here are the steps I'm taking now.

const http=require('http');
constfs=require('fs');

const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer();

server.on('request', function(req,res){
  if(req.url==="/js/index.js"){
    fs.readFile(__dirname+req.url, function(err,data){
      res.writeHead(200, {'Content-Type': 'text/javascript', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'});
      res.write(data);
      res.end(); 
    })
  }
})

server.listen (port, hostname)
forever start server.js
localhost:3000/js/index.js#Accessed from Browser

node.js

2022-09-29 20:25

3 Answers

Get the contents of the javascript file in the source with readFile
text/javascript
Returns the header as .
Therefore, the browser also returns text/javascript in the header, and the contents are Javascript, so I think it is received as a JS file like a regular web service

As a basis for routing, I think you can write the process you want to write in the if statement.

 if(req.url==="/js/index.js"){
    // I think you can write down the process you want to write here.
  }

Also, if you look into NodeJS routing, you will find many things.
I think I often use Express.Please try this as a reference.


2022-09-29 20:25

I will answer based on the subject line.
If you see the contents of /js/index.js on your browser,
mode.js is working (as it is waiting on port 3000).

I don't know why the contents are displayed...

res.write(data);

It's just displayed as it is.(as implemented)

If you simply want to run index.js, instead of server-side Node.js,
Why don't you try Node.js normally?
(The index.js content is also unknown, so I will answer it at this point.)


2022-09-29 20:25

It was a misunderstanding.Reading the file in fs.readFile and returning it as text/javascript was just a browser-readable return of js, and if you wanted to run node.js to get the result, you could only require('/js/index.js')


2022-09-29 20:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.