DEV Community

Cover image for Express handle request body
Andi Ismail
Andi Ismail

Posted on

Express handle request body

git clone https://github.com/andiks2018/JvalleyExpress-membuatApi.git express_req_body
cd express_req_body
npm install //akan install deppendency yang kita butuhkan
dir
code .
npx prisma db push

Enter fullscreen mode Exit fullscreen mode

ada error env prisma hilang sehingga db psuh gak bisa dilakukan, kita buat file baru namanya .env
npm install -g nodemon
npm run dev //menjalankan aplikasi

//.env

DATABASE_URL = "file:./db.slite" //database berbentuk file
Enter fullscreen mode Exit fullscreen mode

sekarang kita ulangi kembali prisma db push

Image env prisma berhasil

kita menggunakan nodemon untuk menjalankan express,

//package.json

{
  "name": "express_simpleapi",
  "version": "1.0.0",
  "description": "",
  "main": "app/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon --exec babel-node app/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@prisma/client": "^4.7.1",
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "prisma": "^4.7.1"
  },
  "devDependencies": {
    "@babel/cli": "^7.19.3",
    "@babel/core": "^7.20.5",
    "@babel/node": "^7.20.5",
    "@babel/preset-env": "^7.20.2"
  }
}
Enter fullscreen mode Exit fullscreen mode

Image gambar

Image restclien extension

kita buat file tester.rest

Image apa ini

//tester.rest (akan muncul tulisan send request)

### create notes

POST http://localhost:9000/note/create?title=test title&content=ini kontentnya&author=andiismail
Enter fullscreen mode Exit fullscreen mode

kita klik send request akan muncul response 200

Image response

sekarang kita buat read notenya, klik send request dan lihat responsnya

### read notes
GET http://localhost:9000/note/read
Enter fullscreen mode Exit fullscreen mode

ini hasilnya

Image response lagi

kita ganti const{title, content, author}= req.querymenjadi const{title, content, author}= req.body

untuk mnghabdle data json, kita perlu middle ware

//index.js

// sekaramg kit sudah bisa menggunakan es-6 di javascript
import express from "express";
import db from "../prisma/connection";

const app = express()

//midleware
app.unsubscribe(express.json())


//route
app.post("/note/create", async (req, res)=>{
    //console.log(req.headers)

    const{title, content, author}= req.body
    const createNote = await db.notes.create({
        data : {
            title : title,
            content : content,
            author:author
        }
    })
    res.status(200).json({
        //success :true,
        //message:"server berhsil terhubung"
        success : true,
        data : createNote  
    })
})

//params
app.get("/note/read", async(req, res)=>{
    const readNotes = await db.notes.findMany()

    res.status(200).json({
        success :true,
        data : readNotes
    })
})

//listener
app.listen(9000, ()=>{
    console.log('server beckend berjalan..')
})
Enter fullscreen mode Exit fullscreen mode

kita sebelumnya telah merubah dari query menjadi body serta menabah middleware. selanjuntnya kita buat file note_routes.js

kita cut file di index.js get dan post (//params dan //route).

//route
app.post("/note/create", async (req, res)=>{
    //console.log(req.headers)

    const{title, content, author}= req.body
    const createNote = await db.notes.create({
        data : {
            title : title,
            content : content,
            author:author
        }
    })
    res.status(200).json({
        //success :true,
        //message:"server berhsil terhubung"
        success : true,
        data : createNote  
    })
})

//params
app.get("/note/read", async(req, res)=>{
    const readNotes = await db.notes.findMany()

    res.status(200).json({
        success :true,
        data : readNotes
    })
})
Enter fullscreen mode Exit fullscreen mode

kita pindahkan ke note_routes.js ganti app jadi note_routs

//note_routes.js

import express from "express";
import db from "../../prisma/connection"
const note_routes = express.Router()

//route
note_routes.post("/note/create", async (req, res)=>{
    //console.log(req.headers)

    const{title, content, author}= req.body
    const createNote = await db.notes.create({
        data : {
            title : title,
            content : content,
            author:author
        }
    })
    res.status(200).json({
        //success :true,
        //message:"server berhsil terhubung"
        success : true,
        data : createNote  
    })
})

//params
note_routes.get("/note/read", async(req, res)=>{
    const readNotes = await db.notes.findMany()

    res.status(200).json({
        success :true,
        data : readNotes
    })
})

export default note_routes
Enter fullscreen mode Exit fullscreen mode

kita kembali ke index.js

//index.js

import express from "express";
import note_routes from "./routes/note_routes";

const app = express()

//midleware
app.use(express.json())

//listener
app.listen(9000, ()=>{
    console.log('server beckend berjalan..')
})
Enter fullscreen mode Exit fullscreen mode

masih error,

https://www.youtube.com/watch?v=l8WPWK9mS5M
https://www.youtube.com/watch?v=4T6EXrxwctI&t=4526s

Top comments (0)