I have created a simple node server with CORS enabled. But when I do node server.js, it's throwing error

Viewed 240
const express = require('express');

const cors = require('cors');

const app = express();



app.use(cors());

app.get('https://jsonplaceholder.typicode.com/todos/1', (req, res) => {
  res.send({ express: 'Hello From Express' });
});

const port = 3030;
app.listen(port, () => console.log(`Server running on port${port}`));

I have created a simple node server with CORS enabled. But when I do, node server.js, it throws a particular error, which I'm not able to figure it out.

internal/modules/cjs/loader.js:596
    throw err;
    ^

Error: Cannot find module 'C:\Users\Cnetric\Desktop\reactonline\server.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15)
    at Function.Module._load (internal/modules/cjs/loader.js:520:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
    at startup (internal/bootstrap/node.js:238:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:572:3)

Can someone please help me on this. I'm not able to troubleshoot. I'm new to node and not able to figure it out.

My folder structure

reactonline-> src, public, node_modules, package.

Then under the src folder, all my files are there.

enter image description here

2 Answers

It tries to find the file in the wrong location:

'C:\Users\Cnetric\Desktop\reactonline\server.js'

It's actually in:

'C:\Users\Cnetric\Desktop\reactonline\src\server.js'

You should run the node command in the correct folder.

As mentioned in comments. Your package.json file is in root folder and you have server.js in src folder which is the problem.

Move your server.js file under your root folder i.e., reactonline and resolve path issues if you have included any files in server.js. It will work now

Regarding getting data from external source you need to use node-rest-client library. Check here for more details about the library

First install it

npm install -s node-rest-client

then here

const express = require('express');

const cors = require('cors');
const Client = require('node-rest-client').Client;//import it here
const app = express();

app.use(cors());

app.get('/', (req, res) => {

   var client = new Client();

   // direct way
   client.get("https://jsonplaceholder.typicode.com/todos/1", (data, response) => {
    res.send({ express: 'Hello From Express', data: data });
   });
});

const port = 3030;
app.listen(port, () => console.log(`Server running on port${port}`));
Related