CORS
什么是CORS
大概知道什么是CORS,偶尔也遇到过,想自己实现个例子
用Golang代码实现
因为CORS只要域名,协议,端口之一不一样就算,我们在本机起两个web服务,只是监听端口不一样
服务1
监听本机1718端口,在后端渲染了一个页面,在页面里用Ajax访问服务2(1719端口)
在Ajax请求里请求成功会在浏览器的console里输出服务2返回的内容
package main
import (
"flag"
"html/template"
"log"
"net/http"
)
var templ = template.Must(template.New("qr").Parse(templateStr))
func main() {
flag.Parse()
http.Handle("/", http.HandlerFunc(QR))
err := http.ListenAndServe(":1718", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func QR(w http.ResponseWriter, req *http.Request) {
templ.Execute(w, req.FormValue("s"))
}
const templateStr = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>QR Link Generator</title>
<script>
let invocation = new XMLHttpRequest();
let url = 'http://127.0.0.1:1719';
function callOtherDomain() {
alert("callOtherDomain");
if (invocation) {
invocation.open('GET', url, true);
invocation.onreadystatechange = function () {
if (invocation.readyState === XMLHttpRequest.DONE && invocation.status === 200) {
console.log(invocation.responseText)
}
};
invocation.send();
}
}
callOtherDomain();
</script>
</head>
<body>
{{if .}}
<img src="http://chart.apis.google.com/chart?chs=300x300&cht=qr&choe=UTF-8&chl={{.}}" />
<br>
{{.}}
<br>
<br>
{{end}}
<form action="/" name=f method="GET">
<input maxLength=1024 size=70 name=s value="" title="Text to QR Encode">
<input type=submit value="Show QR" name=qr>
</form>
</body>
</html>
`
服务2
监听1719端口,只有一个路由就是返回字符串的"hello,world"
语句1是控制能否跨域访问的关键
package main
import (
"flag"
"log"
"net/http"
)
func main() {
flag.Parse()
http.Handle("/", http.HandlerFunc(QR))
err := http.ListenAndServe(":1719", nil)
if err != nil {
log.Fatal("ListenAndServe:", err)
}
}
func QR(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*") // 语句1
w.Write([]byte("hello,world"))
}
语句1被注释的情况
打开浏览器访问服务1在浏览器命令行看到如下,可以看到被同源策略阻挡了
Access to XMLHttpRequest at 'http://127.0.0.1:1719/' from origin 'http://127.0.0.1:1718' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
语句1未被注释的情况
打开浏览器访问服务1在浏览器命令行看到服务2成功的返回