0

I'm trying to set up a local server using node.js and the server works fine on the terminal but i got this error on the browser "Uncaught ReferenceError: require is not defined" any help will be appreciated thanks in advance

// Setup empty JS object to act as endpoint for all routes
projectData = {};

// Require Express to run server and routes
const express=require('express');

//Require cors and body parser
const cors=require('cors');
const bodyParser=require('body-parser');

// Start up an instance of app
const app=express();

//Setting port to listen to
const port=3200;

//server testing
server=app.listen(port,function(){
    console.log(`server running on port ${port}`)
})

/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
app.use(cors());

// Initialize the main project folder
app.use(express.static('website'));


// Setup Server
//setting up a get route
app.get('/getRoute',getCallback())
//get function
function getCallback(req,res){
    res.send(projectData);
    console.log(projectData);
}

//setting up a post route
app.post('/postRoute',postCallback())
//get function
function postCallback(request,response){
    newData={
        temperature:request.body.temperature,
        date:request.body.date,
        userResponse:request.body.userResponse
    }

    projectData.push(newData);
}

that's the server side code for getting temperature information and showing it in the browser

  • Does this help you? https://stackoverflow.com/questions/5168451/javascript-require-on-client-side – Tushar Shahi May 26 '21 at 06:53
  • I already tried using browseify and just tried adding "require.js" but that didn't solve the problem....I don't know what I'm doing wrong – Marco Nashaat May 26 '21 at 07:07
  • You can't run a server inside the browser or any code that uses the nodejs `require()`. I'd suggest you show the actual code that is generating the error in the browser and explain what you were trying to do with that code in the browser. – jfriend00 May 26 '21 at 07:08
  • Express can only run on the backend, not in a browser! – sandrooco May 26 '21 at 07:18

2 Answers2

0

This is because require() does not exist in the browser/client-side. Use <script>...</script> tag in browser.

Ashutosh Patole
  • 926
  • 1
  • 7
  • 23
0

Try using browserify, and also it is a nice quick extension to use if you are working on a small project that you want to get working on the client-side right away. check out this article it might help you.