每年培训输出1000+合格IT工程师
培训影响全国各大知名IT企业和部门

搭建restful服务应用(前端+后台)

function fetchGet() {
    fetch("http://localhost:8000/api/users").then(response=>{
        response.json().then(data=>{
            console.log(data)
        })
    })
}

function fetchPost() {
    fetch("http://localhost:8000/api/adduser",{
        method:"POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body:"a=1&b=2"
    })
}

function fetchByAxios() {
    axios.get("http://localhost:8000/api/users")
        .then(res=>{
            console.log(res)
        })
}


function fetchByAxiosPost() {
    axios({
        url:"http://localhost:8000/api/adduser",
        method:"post",
        data:{
            name:"zhangsan",
            age:30
        }
    }).then(res=>{
        console.log(res.data)
    })
}

fetchByAxiosPost()


const express = require('express')
const router = express.Router()
const ProductService = require("../services/product/ProductService")

/**
 * 解决访问的跨域问题
 */
router.all("*",(req,res,next)=>{
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/
    else  next();
})

 

/**
 * API 查询产品信息的接口
 * METHOD verb : CURD post|put|delete|get|options
 */
router.get("/api/get",(req,res)=>{
    console.log(req.query.title)
    let where = {}
    if(req.query.title){
        where.title = req.query.title
    }
    ProductService.getByWhere(where,(err,results)=>{
        res.json(results)
    })
})

/**
 *  API 商品添加的API
 */
router.post("/api/add",(req,res)=>{

    let data = req.body || {}
    console.log(data)
    let product ={
        title:"test",
        desc:"test",
        pics:"test",
        price:1
    }
    ProductService.addData(product,(err)=>{
        console.log(err)
        res.json("添加成功了")
    })
})

/**
 * API 删除商品的API
 */
router.delete("/api/del",async (req,res)=>{
    console.log("delete")
    let result = await ProductService.deleteDataByWhere({title:"adfadf"})
    res.json(result)
})


/**
 * API 更新商品的API
 */
router.put("/api/update",(req,res)=>{
    res.json({err:"put success"})
})



module.exports = router;
赞(3) 打赏
未经允许不得转载:徐礼文的技术博客 » 搭建restful服务应用(前端+后台)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏