跨域請求的解決辦法
阿新 • • 發佈:2020-12-22
跨域請求的問題
問題說明
同源策略是一個重要的安全策略,它用於限制一個origin的文件或者它載入的指令碼如何能與另一個源的資源進行互動。它能幫助阻隔惡意文件,減少可能被攻擊的媒介。但是有時我們想訪問時就會遇到跨域請求的限制,在這裡說一下解決方案。
需要訪問後端資料的前端表格程式碼:
<template>
<div>
<el-table :data="tableData" style="width: 100%" size="mini" >
<el-table-column
prop="name"
label="直接顯示名字"
width="180">
</el-table-column>
<el-table-column label="日期" width="180">
< template slot-scope="scope">
<i class="el-icon-time"></i>
<span style="margin-left: 10px">{{ scope.row.date }}</span>
</template>
</el-table-column>
< el-table-column label="姓名" width="180">
<template slot-scope="scope">
<el-popover trigger="hover" placement="top">
<p>姓名: {{ scope.row.name }}</p>
<p>住址: {{ scope.row.address }}</p>
<div slot="reference" class="name-wrapper">
<el-tag size="medium">{{ scope.row.name }}</el-tag>
</div>
</el-popover>
</template>
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">編輯</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">刪除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Table',
components: {
},
data() {
return {
tableData: []
}
},
methods: {
},
created() { // 看這裡,看這裡,看這裡!!!!!
//請求後端的資料,後端不進行處理時,這樣是訪問不到資料,會遇到跨域請求的問題
axios.get('http://127.0.0.1:8080/web/user')
//在前端寫死的json資料,用來測試訪問的
// axios.get('stu.json')
.then((res)=>{
this.tableData = res.data
})
.catch(function (error) {
console.log(error);
});
}
}
</script>
<style>
</style>
前端表格中的created()的程式碼:
created() {
//請求後端的資料,後端不進行處理時,這樣是訪問不到資料,會遇到跨域請求的問題
axios.get('http://127.0.0.1:8080/web/user')
//在前端寫死的json資料,用來測試訪問的
// axios.get('stu.json')
.then((res)=>{
this.tableData = res.data
})
.catch(function (error) {
console.log(error);
});
}
後端的UserController程式碼:
package com.neuedu.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.neuedu.entity.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Keafmd
*
* @ClassName: UserController
* @Description: UserController
* @author: 牛哄哄的柯南
* @date: 2020-12-17 14:20
*
*
* http://127.0.0.1:8080/web/user
*/
@WebServlet(name="UserController" ,urlPatterns = "/user")
public class UserController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//可以從資料庫獲取,我們後端這裡暫時這樣寫。
List userList = new ArrayList();
userList.add(new User(1,"牛哄哄的柯南1","某某省某某市1",new Date()));
userList.add(new User(2,"牛哄哄的柯南2","某某省某某市2",new Date()));
userList.add(new User(3,"牛哄哄的柯南3","某某省某某市3",new Date()));
userList.add(new User(4,"牛哄哄的柯南4","某某省某某市4",new Date()));
userList.add(new User(5,"牛哄哄的柯南5","某某省某某市5",new Date()));
userList.add(new User(6,"牛哄哄的柯南6","某某省某某市6",new Date()));
String json = JSON.toJSONString(userList, SerializerFeature.WriteDateUseDateFormat );
//轉換格式,讓前端接收
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
out.write(json);
out.flush();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
直接訪問http://127.0.0.1:8080/web/user時顯示的是一個json物件,當我們使用80埠訪問前端程式碼時,因為前端會通過8080埠請求後端的json物件,這時需要同時訪問後端的8080的埠和前端的80埠,這種情況瀏覽器預設是不允許的,這時就會出現跨域請求的問題。
解決辦法
解決辦法就是我們在後端設定resp.addHeader("Access-Control-Allow-Origin","*");
允許同時訪問,最好是寫個過濾器。
在後端寫個CrossFilter過濾器。
CrossFilter程式碼:
package com.neuedu.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Keafmd
*
* @ClassName: CrossFilter
* @Description:
* @author: 牛哄哄的柯南
* @date: 2020-12-17 14:47
*/
//過濾所有的
@WebFilter(urlPatterns = "/*")
public class CrossFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) response;
resp.addHeader("Access-Control-Allow-Origin","*");
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
看完如果對你有幫助,感謝點贊支援!
如果你是電腦端,看到右下角的 “一鍵三連” 了嗎,沒錯點它[哈哈]
加油!
共同努力!
Keafmd