12

Building a Full Stack Application From Scratch with Svelte and Node (PART 7) — P...

 3 years ago
source link: https://tahazsh.com/fullstack-app-with-svelte-and-node-part-7
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

It's now the time to switch to creating the backend project. Since the main focus of this series is creating an app with Svelte and Sapper, you can create the backend app using any language/framework you want.

But I thought it would be more fun to show you how to create everything from scratch, and it's also an opportunity for developers who have never built an API with Node to get an idea how it's done.

Creating the project

Create a new folder and name it news-app-backend, and inside it create package.json.

Now let's start by installing those packages (but before that make sure package.json contains {}):

npm install express cors cross-env

Next, create app.js and these folders: routes/, models/, handlers/. So your project should look like this:

.
├── app.js
├── handlers
├── models
├── node_modules
├── package-lock.json
├── package.json
└── routes
  • app.js: is the entry file for the app.
  • models/: will contain all of our mongoose models
  • routes/: we'll define and handle our API endpoints in this folder
  • handlers/: for this project, we'll only define the JWT handler using passport

Running the app

Add the following code in app.js:

const app = require('express')()
const cors = require('cors')
const bodyParser = require('body-parser')

app.use(cors())

// support parsing json request data
app.use(bodyParser.json())

app.get('/', (req, res) => {
  res.end('hello world!')
})

// 404 error handler
app.use((req, res) => {
  res
    .status(404)
    .json({
      message: 'not found'
    })
})

// other errors handler
app.use((err, req, res, next) => {
  let error = {
    status: err.status || 500,
    message: err.message || 'Something went wrong!'
  }
  if (process.env.NODE_ENV === 'development') {
    error['stack'] = err.stack
  }
  res
    .status(err.status || 500)
    .json(error)
})

// running the app
const port = process.env.PORT || 5000
app.listen(port, () => console.log(`news app backend is running on port ${port}`))

So we've only defined a single endpoint / that displays "hello world". We've also defined the 404 and other error handlers below that.

And to make sure we don't get a CORS error when the frontend interacts with it, we whitelisted all domains with app.use(cors()).

Now let's check if this works by running: node app.js and checking your browser at http://localhost:5000. You should see the "hello world" message.

1.png

Adding running scripts

Let's make it easier to run our app in dev and production modes by adding the following npm scripts to package.json:

{
  "scripts": {
    "dev": "cross-env NODE_ENV=development nodemon app.js",
    "start": "cross-env NODE_ENV=production node app.js"
  },
  "dependencies": {
    "cors": "^2.8.5",
    "cross-env": "^7.0.2",
    "express": "^4.17.1"
  }
}

So to run it in development mode, run npm run dev. And to run it in production mode, run npm run start.

Note how we're using nodemon in the dev script so we don't have to manually re-run the app for every change we make.

So let's install nodemon with this:

npm install -D nodemon

Setting up our database

We're going to use MongoDB for our database. And there's no better way to use it than with Mongoose.

But before you install mongoose, you need to make sure MongoDB is installed on your machine. Check the docs to install the one for your OS.

After it's installed and running, create a new database and name it sveltenewsapp. (You can use MongoDB Compass to easily manage your databases, data, etc.)

Once that's created, install mongoose on your project:

npm install mongoose

Connecting to our database

In app.js, import mongoose like this:

const mongoose = require('mongoose')

Below the import section, connect to your database with this code:

const MONGODB_URI = 'mongodb://127.0.0.1:27017/sveltenewsapp'

mongoose.connect(MONGODB_URI, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true
})

mongoose.connection.on('error', (err) => {
  console.error('Database connection error:', err)
})

Make sure to update MONGODB_URI if you're hosting your database somewhere else.

Now re-run the app and check your terminal to make sure your app is connected to the database successfully without any errors.

What's next?

Now our backend app is up and running, let's define our mongoose models — User, Story, and Comment. This is what we'll do in the next part.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK