Basic Express Server Using Replit.com
Tags: node, javascript, fetch, http
Published: 2021-11-01 20:17:14

In this post, I will introduce how to set up the most basic Express server in Node.JS, and how to see that your server is ready to accept requests. We will also use [CodePen](codepen.io) to write a fetch GET request to your server so you can see a basic request and response from a frontend (built with CodePen) to a backend (built with Replit).

Replit.com and Codepen.io are tools I use all the time when I want to test some code or play around with something. If you want to practice writing HTTP requests, this is a great way to get you set up to do that.

## Set up your Express server

Go to [Replit](https://replit.com). Click on the **Create Repl** button. Search templates for Node.js. Replit will assign a random name to your repl but you can change it to whatever makes sense to you.

Now we will set up the Express server.

*You can use Node.JS by itself to create a server, but the Node.JS Express framework provides an easier way to quickly set one up. If you really want to see how to build a Node server without using Express, take a look at this page on [MDN](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Node_server_without_framework).* 

First, we must require the framework Express and run the express application:

```js
const express = require('express');
const app = express();
```

*In Replit, if you use the* `require('express')` *syntax, it will auto-install express for you. Otherwise, you can type* ***npm install express*** *in the shell.*

In order to enable CORS and to avoid getting a CORS error, we can install the Express CORS middleware package. We will have to place it before we call the express() method, so your file should look like this:

```js
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
```
The final step to setting up an Express server is to make your server listen for connections on a given path. We will create a port and use the listen() method to listen for connections. You can use any number between 1 and 65535, but [the traditional port number for web servers is 80](https://computer.howstuffworks.com/web-server8.htm). Use whatever you want.

```js
const port = 8080;
app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
```

Lastly, we will set up an endpoint to respond to GET requests:

```js
app.get('/', (req, res) => {
  res.json('Hello World')
});
``` 

This endpoint includes 
- an instance of Express (`app`) 
- the HTTP request method (in this case, `get`)
- a path (`'/'`) 
- a function to handle the request. That function will take in the request and it will respond by sending a message back to the client (frontend). Read more at [expressjs.com](http://expressjs.com/en/starter/basic-routing.html) to learn about basic routing.

Here is our server:

```js
const express = require('express');
const cors = require('cors');
const app = express();
const port = 8080;

app.use(cors());

app.get('/', (req, res) => {
  res.json('Hello World')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
```
Make sure you click the big button at the top of the repl that says **Run** to start up your server. If you want to see my actual repl, it's [here](https://replit.com/@SandraR/Basic-Express-Server#index.js).

## Set up your Frontend at CodePen

Now, we want to create a frontend so we can have the frontend client make a request to the backend server we just built. And we want to see the response on the front end.

Go to [CodePen](codepen.io) and create a new 'pen'. Here is my [pen](https://codepen.io/sandrarodgers/pen/VwzrZPe) for this article if you need an example.

In the Javascript section of the pen, we will use the `fetch()` method to write a request to our server to fetch the message (the message we set up our `get` endpoint to send back - 'Hello World'). 

*The `fetch()` method comes from the Fetch API, which is a client-side browser API. It is not actually part of the Javascript language itself, but is one of the many APIs that is built into the web browser and sits on top of the Javascript language. Read more at [MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Introduction) to learn about the awesomeness that is the browser Web APIs.*

A basic fetch request will include:
- the `fetch()` method
- the endpoint URL (the path to the resource we want to fetch). The path includes the url + the path we put in our endpoint, which was '/'. 

```js
fetch('https://basic-express-server.sandrar.repl.co/')
    .then(response => response.json())
    .then(data => {console.log(data)})
```
*To create a url to reach your server on Replit.com, use the structure: /[repl-name].[username].repl.co/*

Calling the fetch method with the endpoint url returns a promise, so we can use the Javascript `.then()` to wait for the response. Inside the callback of the `.then()`, we will deal with the response:

```js
.then(response => response.json())
```
We want to take the JSON content from the response object that is sent back. So we use the `json()` method on the response. That `json()` method also returns a promise. 

```js
.then(data => {console.log(data)})
```

So we use .`then()` again, and in the second .then() we now have the response parsed into JSON that we can read, so we console.log that parsed response.


Then we must open the console to read it. Look for a small button in CodePen that says 'console' and click on it to open the nifty CodePen console. Or you can just open your devtools and check in there. You should see

``Hello World``

And that's it! We see that we have correctly built a server with an endpoint. We can make a request to that endpoint and get back the response that we expect.

I hope this was helpful to you!