如何解决前端跨域问题 ----- 通过CORS、NGINX、JSONP解决

深度分析前端跨域

    • 产生跨域的原因
    • 如何解决跨域
      • 后端处理 CORS跨域
      • 前端配置代理服务
      • JSONP
      • 将前后端服务放在同一服务器下

产生跨域的原因

由于浏览器的安全策略,避免在跨域名访问的时候页面资源被篡改。
当请求源地址目的地址协议域名端口有一个不同就会产生跨域。
本文主要提供三个方式来解决跨域问题,分别是服务端配置Access-Control-Allow-Origin、反向代理、JSONP

如何解决跨域

后端处理 CORS跨域

在后端响应头增加 Access-Control-Allow-Origin配置

//允许来自 www.google.com 源访问
Access-Control-Allow-Origin:www.google.com
//允许所有源访问
Access-Control-Allow-Origin:*

如果资源是html页面,可以设置header的meta标签

<meta http-equiv="Access-Control-Allow-Origin" content="*">

node.js 服务端配置

const http = require("http")
const port = 8001
const hosthame = "localhost"
const server = http.createServer(function (request, response) {
  response.setHeader("Content-Type", "text/plain")
  response.statusCode = 200
  response.end("Hello World!")
})
server.listen(port, () => {
  // 终端打印如下信息
  console.log(`Server running at http://${hosthame}:${port}/`)
})

启动后服务端对应的地址为http://localhost:8001/启动node服务
前端发axios请求给到服务端

<script setup>
import axios from 'axios'
axios.defaults.baseURL = 'http://localhost:8001/';
axios.post().then((res) => {
  console.log(res)
})
</script>

启动前端工程对应地址为http://localhost:3000/
如何解决前端跨域问题 ----- 通过CORS、NGINX、JSONP解决_第1张图片
两个地址的端口号不同请求时发生跨域,发生cors错误
如何解决前端跨域问题 ----- 通过CORS、NGINX、JSONP解决_第2张图片
此时修改node.js 服务端配置,服务端配置 Access-Control-Allow-Origin允许所有源的访问

const http = require("http")
const port = 8001
const hosthame = "localhost"
const server = http.createServer(function (request, response) {
  response.setHeader("Content-Type", "text/plain")
  response.setHeader("Access-Control-Allow-Origin", "*") // 服务端配置 Access-Control-Allow-Origin
  response.statusCode = 200
  response.end("Hello World!")
})
server.listen(port, () => {
  // 终端打印如下信息
  console.log(`Server running at http://${hosthame}:${port}/`)
})

重启服务,重新发起请求,成功获取响应
如何解决前端跨域问题 ----- 通过CORS、NGINX、JSONP解决_第3张图片

前端配置代理服务

可以有两种方式来配置反向代理
1.通过配置反向代理NGINX来实现代理转发

devServer: {
   //设置基本目录结构
    contentBase: [path.resolve(__dirname, '../')],
    //服务器的IP地址,可以使用IP也可以使用localhost
    host: '0.0.0.0',
    //服务端压缩是否开启
    compress: true,
    //配置服务端口号
    port: '1337',
	proxy: {
		'/api': {
			target: 'xxxxxxxx', // 目的地址
			changeOrigin: true,
			pathRewrite: {
				'/api': ''//代理的路径
			}
		}
    }
}

2.直接修改nginx配置文件
severProxy:配置目的地址
location:待反向代理的文件路径
如何解决前端跨域问题 ----- 通过CORS、NGINX、JSONP解决_第4张图片

JSONP

可以实现跨域读取数据,基于浏览器支持以

你可能感兴趣的:(前端博学了没,前端,nginx,javascript)