Skip to content

Commit

Permalink
补充跨域相关
Browse files Browse the repository at this point in the history
  • Loading branch information
onresize committed May 24, 2024
1 parent 891a108 commit e55c7f4
Showing 1 changed file with 60 additions and 1 deletion.
61 changes: 60 additions & 1 deletion docs/技术总结/踩坑总结/跨域相关.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,4 +106,63 @@ app.listen(3000);
console.log('Proxy server is listen at port 3000...');
```

- `3.3、前端开发模式下用构建工具做代理、生产环境用nginx做反向代理`
- `3.3、前端开发模式下用构建工具做代理、生产环境用nginx做反向代理`

### `4.jsonp跨域访问`
- jsonp只能处理get请求、原理通过 `script、img` 这种不受同源策略影响的标签和服务端配合实现跨域通信
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body></body>
</html>

<script>
function jsonp({ url, params, cb }) {
return new Promise((resolve, reject) => {
let script = document.createElement('script')
window[cb] = function (data) {
// 这里的data其实就是服务端给的'456'
resolve(data)
document.body.removeChild(script)
}
params = { ...params, cb }
let arrs = []
for (let key in params) {
arrs.push(`${key}=${params[key]}`)
}
script.src = `${url}?${arrs.join('&')}`
document.body.appendChild(script)
})
}
jsonp({
url: 'http://localhost:3000/say',
params: { wd: '123' },
cb: 'show',
}).then((data) => {
const divDom = document.createElement('div')
divDom.innerText = data
document.body.appendChild(divDom)
})
</script>
```

```js
let express = require('express')
let app = express()

app.get('/say', function (req, res) {
let { wd, cb } = req.query
console.log(wd)
res.end(`${cb}('456')`)
})

app.listen(3000, () => {
console.log('端口启动:http://localhost:3000/say')
})
```

0 comments on commit e55c7f4

Please sign in to comment.