Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js file to run a local server with access-control-allow-origin

I have an html file that has resources in it's directory

(example file tree)

index.html
imgs
  >img1.jpg
  >img2.jpg
  >img3.jpg
js
  >js1.js
  >js2.js

How do I run a node.js server that will allow me to view the HTML file, as well as allow me to access certain websites with the access-control-allow-origin *

I am unfamiliar with node, so the simpler, the better!

Extra: does not necessarily have to be node, just a server that will allow access control

like image 538
Kore Avatar asked Oct 23 '25 23:10

Kore


1 Answers

Since You're learning and starting from scratch so it's preferred to learn how it's done than installing supper-pupper swiss knife toolset that will hide the logic from You and make You boring lazy developer.

If You just want to achieve quick result and don't want to learn - You may use serve package that will do what You need.

But if You're learning nodejs from zero to hero so read my answer.

It's better to do simple things.

Let's go (:

Create some folder and inside of it do following commands in terminal (or cmd in windows os):

1) Init app:

npm init

2) Install express module:

npm i --save express

3) Install cors module/middleware:

npm i --save cors

4) Create public folder and put Your html files there

5) Create app.js file in sibling folder with public:

"use strict";

const
  express = require('express'),
  app = express(),
  cors = require('cors');

app.use(cors()); // attach cors middleware (must be set before of most route handlers to populate appropriate headers to response context)
app.use('/', express.static('public'));
app.listen(8080, () => console.log('APP STARTED'));

6) Run it: node app.js

7) Open in browser: http://127.0.0.1:8080

for more stuff search in YouTube for nodejs express tutorials, nodejs mean stack tutorials and etc. (:

like image 153
num8er Avatar answered Oct 25 '25 12:10

num8er



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!