package main
import (
"github.com/gin-gonic/gin"
"log"
".NET/http"
)
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
App := gin.Default()
app.Use(cors) //这是设置中间件,其目的是响应跨站请求
app.GET("/api", func(c *gin.Context) {
view(c)
c.JSON(200, gin.H{"code": 201}) //根据返回的code值区别不同的请求,201是GET
})
app.POST("/api", func(c *gin.Context) {
view(c)
c.JSON(200, gin.H{"code": 202}) //根据返回的code值区别不同的请求,202是POST
})
app.PUT("/api", func(c *gin.Context) {
view(c)
c.JSON(200, gin.H{"code": 203}) //根据返回的code值区别不同的请求,203是PUT
})
app.DELETE("/api", func(c *gin.Context) {
view(c)
c.JSON(200, gin.H{"code": 204}) //根据返回的code值区别不同的请求,204是DELETE
})
_ = app.Run("0.0.0.0:8888")
}
func view(c *gin.Context) {
_ = c.Request.ParseForm() //解析form数据
values1 := c.Request.Form //获取到get、post的数据
log.Println(values1)
values2 := c.Request.PostForm //只获取到post数据
log.Println(values2)
}
func cors(c *gin.Context) {
// Access-Control-Allow-Origin,标识允许哪个域的请求,*代表所有的域请求
c.Header("Access-Control-Allow-Origin", "*")
// 响应首部 Access-Control-Allow-Methods 在对 preflight request.(预检请求)的应答中明确了客户端所要访问的资源允许使用的方法或方法列表。
// 例如Access-Control-Allow-Methods: POST, GET, OPTIONS,使用*代表所有
c.Header("Access-Control-Allow-Methods", "*")
// 响应OPTIONS请求
if c.Request.Method == "OPTIONS" {
c.JSON(http.StatusOK, nil)
}
}
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
<hr>
<!-- 测试GET请求-->
<button class="btn btn-primary btn-block" @click="test11">jqueryGET</button>
<!-- 测试POST请求-->
<button class="btn btn-primary btn-block" @click="test12">jqueryPOST</button>
<!-- 测试PUT请求-->
<button class="btn btn-primary btn-block" @click="test13">jqueryPUT</button>.
<!-- 测试DELETE请求-->
<button class="btn btn-primary btn-block" @click="test14">jqueryDELETE</button>
<hr>
</template>
<script>
import $ from "jquery" //引入jquery
export default {
name: 'AboutView',
components: {},
methods: {
test11() {
//通过ajax发送GET请求
$.ajax({
url: "http://172.16.0.251:8888/api",
type: "GET",
data: {"id": "101"},
success: result => {
console.log(result);
}
}
)
},
test12() {
//通过ajax发送post请求
$.ajax({
url: "http://172.16.0.251:8888/api",
type: "POST",
data: {"username": "zhangsan", "password": "123456"},
success: result => {
console.log(result);
}
}
)
},
test13() {
//通过ajax发送put请求
$.ajax({
url: "http://172.16.0.251:8888/api?id=101",
type: "PUT",
data: {"username": "zhangsan", "password": "56789"},
success: result => {
console.log(result);
}
}
)
},
test14() {
//通过ajax发送delete请求
$.ajax({
url: "http://172.16.0.251:8888/api",
type: "DELETE",
data: {"id": "101"},
success: result => {
console.log(result);
}
}
)
},
}
}
</script>
发送请求
结果响应
状态显示