Ahri-珊
day10将分享如何使用fetch请求第三方服务器的资源。
什么是跨域
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。所以我们要访问第三方服务器的资源首先要解决跨域问题。
Access-Control-Allow-Origin
Access-Control-Allow-Origin是HTML5中定义的一种解决资源跨域的策略。
他是通过服务器端返回带有Access-Control-Allow-Origin标识的Response header,用来解决资源的跨域权限问题。
因此,只要在服务器设置Access-Control-Allow-Origin我们就能访问这个服务器的资源了。
node服务器设置方法
const express = require('express')
const http = require('http')
const app = express()
// 跨域设置
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Credentials", true)
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "X-Requested-With")
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8")
next()
})
fetch函数写法
fetch(url, {//访问的服务器地址
method: 'GET',//请求方法
mode: 'cors',//跨域
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then((res) => { console.log(res.status); return res.json() })//将得到的json字符串转换为json对象
.then((data) => {
处理得到的数据
})
.catch((e) => { console.log(e.message) })
}
}
Comments