Steps to Set Up Backend Using Node
For the backend, we will be using Express.js. Here we will create an API endpoint for compiling our code. So let’s create a folder named ‘server‘ which will contain all the backend logic.
Step 1: Type the following commands in the terminal:
mkdir server
cd server
Step 2: Let’s initialize a node.js project:
npm init
Step 3: Let’s install some dependencies:
npm install express cors axios
Dependencies list in package.json file
"dependencies": {
"axios": "^1.7.2",
"cors": "^2.8.5",
"express": "^4.19.2"
}
Step 4: Create a file named ‘index.js‘. This is the only file that will contain all the backend logic. In this file, we will create a POST route that will take the source code, language, and input if any, from the frontend. After getting those, it will then call the code compilation API (opensource) whose response will be sent back to the frontend where the result will be shown on the output screen.
// Filename - index.js
const express = require("express");
const cors = require("cors");
const Axios = require("axios");
const app = express();
const PORT = 8000;
app.use(cors());
app.use(express.json());
app.post("/compile", (req, res) => {
//getting the required data from the request
let code = req.body.code;
let language = req.body.language;
let input = req.body.input;
if (language === "python") {
language = "py"
}
let data = ({
"code": code,
"language": language,
"input": input
});
let config = {
method: 'post',
url: 'https://codexweb.netlify.app/.netlify/functions/enforceCode',
headers: {
'Content-Type': 'application/json'
},
data: data
};
//calling the code compilation API
Axios(config)
.then((response) => {
res.send(response.data)
console.log(response.data)
}).catch((error) => {
console.log(error);
});
})
app.listen(process.env.PORT || PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
Now, we have successfully created the POST request route which we will call from the frontend.
Start the back-end server:
node index.js
The server will listen on localhost port 8000
Start the front-end application:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Build an Online Code Compiler using React.js and Node.js
In this article, we will learn how to build an online code compiler using React.js as frontend and Express.js as backend. Users will be able to write C, C++, Python, and Java code with proper syntax highlighting as well as compile and execute it online. The main objective of building an online compiler is to facilitate any user such that programs of any language can be compiled and run without downloading any IDE (Integrated Development Environment) or compiler.
Prerequisites:
The pre-requisites for this project are:
- Basic knowledge of HTML, CSS & JavaScript
- Basic knowledge of React.js
- Basic knowledge of API, Express.js, Node.js
Contact Us