小言_互联网的博客

跨域请求的解决办法

505人阅读  评论(0)

跨域请求的问题

问题说明

同源策略是一个重要的安全策略,它用于限制一个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


转载:https://blog.csdn.net/weixin_43883917/article/details/111316232
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场