35
loading...
This website collects cookies to deliver better user experience
node -v
.mkdir restapi
cd restapi
npm init -y
touch app.js
-y
which simply means answers "yes" to all of the questions. If you skip this flag, then you will have to answer them manually. In the last part, we create the file app.js
where our API's code will live.package.json
file, which will let us use ES6 way of importing modules// "commonjs" style
const express = require("express");
// ES6 style
import express from "express";
package.json
file and under "description"
add the following line "type": "module",
"start": "node app"
"scripts"
block. This will let you use npm start
command just like you have probably used before with React for example, otherwise you would have to type node app
each time in the terminal to execute app.js
file with Node.js. There is one more detail - Express. Go to the terminal, make sure that your terminal is opened inside of the project folder and type in the following command npm i express
- this command means use the npm package manager, and i
install the package called express
. install
instead of i
and also add the flag --save
to add the module to the package.json file.import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("hello world");
});
.get
which takes 2 parameters req - request
and res - result
. Since we do not care much about the request at this point, just hitting the endpoint with the "GET" method, we will only send back string "hello world" back to the sender.app.listen(5000);
import express from "express";
const app = express();
app.get("/", (req, res) => {
res.send("hello world");
});
app.listen(5000);
npm start
or node app
in the terminal, open your web browser and go to the http://localhost:5000. On that address "hello world" text should be visible. CTRL + C
const app = express();
add following code:app.use(express.json());
app.use(express.urlencoded());
.use
is generally used to add middlewares for the connections made with the express, in this case, we have .json()
and .urlencoded
. These two middlewares will parse JSON files and convert request input, to readable strings and numbers..env
. Let's store our port value inside of such an environmental file.import dotenv from "dotenv";
dotenv.config();
. Now you can create a new file called .env
inside of the same folder. Inside of the .env
file add the following line PORT=5000
. Then go back to the app.js
file, create a variable called port and assign it to the value from the .env
file like that const port = process.env.PORT;
Now you can modify the last line of the code to app.listen(port);
app.listen(port, () => {
console.log(
Listening on port: ${port});
});
`
class MainController {
HelloWorld(req, res) {
return res.send("Hello World");
}
}
export default MainController;
`Listening on port: ${port}
);