【vue】跨域请求成功案例(error:No 'Access-Control-Allow-Origin' header)

本文详细介绍了如何使用axios在前端发起跨域POST请求,并在后端通过设置Access-Control-Allow-Origin响应头来解决跨域问题。提供了具体的代码示例,包括前端Vue组件中axios的配置与请求,以及后端处理跨域请求的Java代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Error:

Failed to load http://xxxx: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

 

一、首先前端:

用的是axios,安装npm i axios -S

在组件内引入:

    import qs from 'qs'

    import axios from 'axios'

    let reqUrl = 'http://192.168.1.180:93/byxwebsite/api/getNewsByType’;

    let reqParams = {

      type: 7,

      limit:6,

      page:1

    }

然后在生命周期钩子里发送请求:

  mounted(){

       axios.post(reqUrl, qs.stringify(reqParams)).then(response => {

                this.testStr = response

         },error =>{

                this.testStr = error

        })

   },

 

二、后台也需要做一些操作,允许所有的请求源头,最少也是我们用的需要允许

public void getNewsByType() {



getResponse().addHeader("Access-Control-Allow-Origin", "*");

String callback = getRequest().getParameter("callback");

String type=getPara("type");

Integer page = getParaToInt("page");

Integer limit=getParaToInt("limit");

if(limit==null || limit==0) {

limit=999;

}

if(page==null || page==0) {

page=1;

}

String sql="select * from tb_news where type="+type+" limit "+(page-1)*limit+","+limit;

/*if(limit!=null) {

sql+=" limit "+limit;

}*/

List<TbNews> list=TbNews.dao.find(sql);

Map<String,Object> map = new HashMap<>();

map.put("data", list);

String jsonp = callback+"("+ JsonKit.toJson(map)+")";//返回的json 格式要加callback()

renderJson(jsonp);

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值