前端培训丁鹿学堂:fetch+cors实现前后端跨域通信

262 阅读1分钟
fetch介绍:

Fetch API提供了一个 JavaScript 接口,用于访问和操纵HTTP的请求和响应等。提供了一个全局 fetch() 方法来跨网络异步获取资源。

fetch 请求默认返回一个promise,通过then可以链式调用,返回的res数据第一层通过json()调用,返回的promise再通过then调用,就是对象数据了。

fetch默认发送get请求

fetch('http://localhost:3000/api/getValue').then(response => {
    return  response.json()
 }).then(res=>{
     console.log(res)
})

fetch发送post请求

let data={
    id:123
}
fetch('http://localhost:3000/api/getValue',{
    method:'POST',
    body:data
})	
.then(response => response.json())
.then(data => console.log(data));
后端(node)使用cors控制解决跨域:

"access-control-allow-origin":'*' // 设置cors头去解决跨域问题

let http = require('http')
let url = require('url')
http.createServer((req,res)=>{
    let data = url.parse(req.url,true)
    res.writeHead(200,{
        "Content-Type":"application/json;charset=utf-8",
        "access-control-allow-origin":'*' // 设置cors头去解决跨域问题
    })
    if(data.pathname === '/api/getValue'){
        res.end(`${JSON.stringify({
            name:'zhangsan',
            age:18
        })}`)
    }else{
        res.end("404")
    }
}).listen(3000,()=>{
    console.log('server run ...')
})