express+mongodb后端初步

npm install express@next mongoose cors --save
const express = require('express')
const app = express()

// 跨域
app.use(require('cors')())
// 静态文件托管
app.use('/', express.static('public')
// 开启json解析
app.use(express.json())

// 连接数据库
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/product', {useNewUrlParser: true})
// 建立模型
const Product = mongoose.model('Product', new mongoose.Schema({
  title: String,
}))

// 接口
// 列表
app.get('/produts', async (req, res) => {
  const data = await Product.find()
  res.send(data)
})
// 详情
app.get('/products/:id' async (req, res) => {
  const data = await Product.findById(req.params.id) 
  res.send(data)
})
// 新增
app.post('/products', async (req, res) => {
  const data = req.body
  const product = await Product.create(data)
  res.send(product)
})
// 修改
app.put('/products/:id', async (req, res) => {
  const product = await Product.findById(req.params.id)
  product.title = req.body.title
  await product.save()
  res.send(product)
})
// 删除
app.delete('/products/:id', async (req, res) => {
  const product = await Product.findById(req.params.id)
  await product.remove()
  res.send({
    success: true
  })
})

// 监听端口
app.listen('3000', () => {
  console.log('http://localhost:3000/')
})

public > index.html


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Documenttitle>
head>
<body>
  <h1>Main Pageh1>
  <a href="http://localhost:3000/products">productsa>
  <script>
    fetch('http://localhost:3000/products').then(res => res.json()).then(data => {
      console.log(data)
    })
  script>
body>
html>

你可能感兴趣的:(express+mongodb后端初步)