rest和ajax学习笔记

        rest简介:

REpresentational State Transfer
表示层状态的传输

Rest实际上就是一种服务器的设计风格

它的主要特点就是,服务器只返回数据服务器和客户端传输数据时通常会使用JSON作为数据格式请求的方法:
GET:加载数据
POST:新建或添加数据
PUT:添加或修改数据
PATCH:修改数据
DELETE :删除数据
OPTION :由浏览器自动发送,检查请求的一些权限 

API(接口) Endpoint (端点)

GET /user

POST /user
DELETE /user/:id

 编写api


const express = require ("express")//引入

const app=express()//解析出来

let Sudent=[
    { id:0,name:'哈哈',age:22,gender:'男'},
    { id:1,name:'嘿嘿',age:18,gender:'女'},
    { id:2,name:'呜呜',age:13,gender:'男'},
    { id:3,name:'嗯嗯',age:22,gender:'女'},

]

//查询列表
app.get('/student',(req,res)=>{
        res.send({
            status:'ok',
            data:Sudent
        })
})
//查询某个
app.get('/student',(req,res)=>{
     const       {id}  = req.body
  const   one=Sudent.filter((f1)=>id!==f1.id )
    res.send({
        status:'ok',
        data:one
    })
})

//添加
app.post('student',(req,res)=>{
    const {id,name,age,gender}=req.body
    const stu={ id:Sudent.at(-1).id+1,
        name,
        age:+age,
        gender}
    Sudent.push(
stu
    )
    res.send({
        status:'ok',
        data:stu
    })
})
//修改
app.put('/student/:id',(req,res)=>{

        const {id,name,age,gender}=req.body
        const EditStu=Sudent.find((f1)=>f1.id===id)
        if(EditStu){
            EditStu.id=id
            EditStu.age=age
            EditStu.name=name
            EditStu.gender=gender
            res.send({
                status:'ok',
                data:EditStu
            })
        }else{
            res.send({
                status:'ok',
                data:'对不起开小差了'
            })

        }

})

app.listen(8080,()=>{//监视服务器
    console.log('服务器已经启动')
})

发送小黄人请求:

import { useState } from 'react'
import './App.css'

function App() {

  const getData=()=>{
      const xhr = new XMLHttpRequest()
      xhr.responseType='json'
      xhr.onload=function(){
        if(xhr.status<300&&xhr.status>=200){
          console.log(xhr.response)

        }
      }
      xhr.open('GET','http://localhost:8080/student')
      xhr.send()
  }
  return (
    <div className="App">
      <button onClick={()=>{
        getData()
      }}>点我获取学生信息</button>
    </div>
  )
}

export default App

CORS(跨域资源共享):

1.    跨域请求

  • 协议,域名,端口号
  •  当我们通过AJAX去发送跨域请求时,浏览器为了服务器的安全,会阻止JS读取到服务器的数据

2.     解决跨域 

 // res.setHeader( 'Access-Control-Allow-Origin','*')//解决跨域 允许所有访问
    res.setHeader( 'Access-Control-Allow-Origin','http://127.0.0.1:5173/')//解决跨域 允许所有访问

app.use((req,res,next)=>{
    // res.setHeader( 'Access-Control-Allow-Origin','*')//解决跨域 允许所有访问
    res.setHeader( 'Access-Control-Allow-Origin','http://127.0.0.1:5173')//解决跨域 允许所有访问
    res.setHeader( 'Access-Control-Allow-Methods','GET,POST')//解决跨域 允许所有访问

    res.setHeader( 'Access-Control-Allow-Headers','Content-type')//解决跨域 允许所有访问

    next()


})

 服务器完整代码


const express = require ("express")

const app=express()

app.use(
    express.json()
)
app.use(
    express.urlencoded({extended:true})
)

app.use((req,res,next)=>{
    // res.setHeader( 'Access-Control-Allow-Origin','*')//解决跨域 允许所有访问
    res.setHeader( 'Access-Control-Allow-Origin','http://127.0.0.1:5173')//解决跨域 允许所有访问
    res.setHeader( 'Access-Control-Allow-Methods','GET,POST')//解决跨域 允许所有访问

    res.setHeader( 'Access-Control-Allow-Headers','Content-type')//解决跨域 允许所有访问

    next()


})
let Sudent=[
    { id:0,name:'哈哈',age:22,gender:'男'},
    { id:1,name:'嘿嘿',age:18,gender:'女'},
    { id:2,name:'呜呜',age:13,gender:'男'},
    { id:3,name:'嗯嗯',age:22,gender:'女'},

]
//查询列表
app.get('/student',(req,res)=>{
    // res.setHeader( 'Access-Control-Allow-Origin','*')//解决跨域 允许所有访问
    res.setHeader( 'Access-Control-Allow-Origin','http://127.0.0.1:5173')//解决跨域 允许所有访问
        res.send({
            status:'ok',
            data:Sudent
        })
})
//查询某个
app.get('/student/:id',(req,res)=>{
     const  id  = req.params.id
  const   one=Sudent.filter((f1)=>id!==f1.id )
    res.send({
        status:'ok',
        data:one
    })
})

//添加
app.post('/student',(req,res)=>{
    const {id,name,age,gender}=req.body
    const stu={ id:Sudent.at(-1).id+1,
        name,
        age:+age,
        gender}
    Sudent.push(
stu
    )
    res.send({
        status:'ok',
        data:stu
    })
})
//修改
app.put('/student/:id',(req,res)=>{

        const {id,name,age,gender}=req.body
        const EditStu=Sudent.find((f1)=>f1.id===id)
        if(EditStu){
            EditStu.id=id
            EditStu.age=age
            EditStu.name=name
            EditStu.gender=gender
            res.send({
                status:'ok',
                data:EditStu
            })
        }else{
            res.send({
                status:'ok',
                data:'对不起开小差了'
            })

        }

})
//删除
app.delete('/student/:id',(req,res)=>{
        const id= req.params.id
        Sudent.forEach((f1,index)=>{
            if(f1.id===id){
                const DeStu=f1
                Sudent.splice(index,1)
                res.send({
                    status:'ok',
                    data:Sudent
                })
                return
            }
        })
        res.status(403).send({ 
            status:'ok',
            data:'对不起开小差了'
        })
     

})

app.listen(8080,()=>{
    console.log('服务器已经启动')
})

fetch使用

import { useState } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'

function App() {
  let [data,setData]=useState<{id:string,age:number,name:string,gender:string}[]>([])
  const getData=()=>{
      fetch('http://localhost:8080/student').then((ret)=>{
              if(ret.status>=200&&ret.status<300){
                return  ret.json()//json返回一个promise对象
              }else{
                  throw new Error()
              }
      }).then((ret)=>{
        setData(ret.data)
      })
      .catch((err)=>{
          console.log('出错了',err)
      })
  }
  const add=()=>{
          fetch('http://localhost:8080/student',{
            method:'post',
            headers: {
              'Content-Type': 'application/json'
              // 'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: JSON.stringify({
              name:'halo',
              age:20,
              gender:'不详'
            }) // body data type must match "Content-Type" header

          })
  }
  return (
    <div className="App">
        <button onClick={()=>{
          getData()
        }}>点我加载数据</button>
        <button onClick={()=>{
          add()
        }}>点我添加数据</button>
        {data.length>0? (
          <ul>
            {data.map((f1)=>{
              return (
                <li>{`${f1.id}--${f1.name}--${f1.age}--${f1.gender}`}</li>
              )
            })}
          </ul>
        ):''}
    </div>
  )
}

export default App

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值