关键字:跨域,Access-Control-Allow-Origin,转码,解码

在做一个前后端分离项目,本来前端项目都可以正常访问后端接口,跨域是这么设置的,接口可以正常访问

@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}

但是在访问一个新的接口时,前端控制台错误:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

后端错误:

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:468) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:260) ~[tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591) [tomcat-embed-core-9.0.29.jar:9.0.29]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.29.jar:9.0.29]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_191]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_191]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.29.jar:9.0.29]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_191]

在网上找了一下解决方法,都是说跨域问题

参考:response设置响应头,解决跨域请求问题,No ‘Access-Control-Allow-Origin’ header is present on the requested resource

解决方法:

1、加注解----对我没用。。。
@CrossOrigin        //跨域
public class BookController {
}
2、设置响应头----还是不行。。。
@PostMapping(path = "/add")
public JsonResult<Object> addBook(Book book, HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control", "no-cache");
}
3、不要参数,试一下,竟然好了。。。。看来出现这个问题的原因是参数的原因

前端请求:

this.$axios({method: 'post', url: '/book/add'}).then(res => {
console.log(res.data)
}).catch(res => {
});

后端接口:

@PostMapping(path = "/add")
public JsonResult<Object> addBook() {
}

又看到一篇文章说可能是参数太多:

参考:Error parsing HTTP request header Note: further occurrences of HTTP header parsing errors will ***

那就继续试,这是我原来要传的参数:
 book: {
name: '',
author: '',
type: '',
publishHouse: '',
price: 0,
description: '',
number: 0,
sales: 0,
status: true,
image: ''
},
我又重新写了一个jsonData,作为参数来代替上面的book
bookTest: {},

先给bookTest里面少放点参数,发起异步请求,竟然成功了。。。

//给里面少放点数据
this.bookTest.name = this.book.name;
this.bookTest.author = this.book.author;
this.bookTest.type = this.book.type; this.$axios({method: 'post', url: '/book/add', params: this.bookTest})
.then(res => {
console.log(res.data)
}).catch(res => {
});

后端代码:

@RequestMapping(path = "/book")
public class BookController {
@PostMapping(path = "/add")
public JsonResult addBook( Book newBook) {
System.out.println("addBook");
System.out.println(newBook);
JsonResult<Object> result = new JsonResult<>();
result = result.builder().data(newBook).message("添加成功").code("1").build();
return result;
}
}
继续增加参数,除了this.bookTest.image = this.book.image;
this.bookTest.name = this.book.name;
this.bookTest.author = this.book.author;
this.bookTest.type = this.book.type;
this.bookTest.publishHouse = this.book.publishHouse;
this.bookTest.price = this.book.price;
this.bookTest.description = this.book.description;
this.bookTest.number = this.book.number;
this.bookTest.sales = this.book.sales;
this.bookTest.status = this.book.status;
仍然可以接收参数,但是加上this.bookTest.image = this.book.image;就又开始报这个错误了,看来问题就是出在了这个image上。

下图的image有问题


2020.3.7更新:

问题已经找出,就出在了image字符串上,因为image这个字符串有特殊字符,必须先转码,传输到后端,再解码
前端:转码,对有特殊字符的字符串进行转码
 this.book.image= encodeURI(JSON.stringify(imageArray))
//imageArray是一个数组,JSON.stringify()是把数组转为字符串,encodeURI()是转码的

转码前,image是这样的:

["/images/ac57249167ce4af5.jpg","/images/9d7bf84bdf40e030.jpg"]

转码后,image是这样的:

%22/images/ac57249167ce4af5.jpg%22%7D,%22/images/9d7bf84bdf40e030.jpg%22%7D%5D

后端:解码
@PostMapping(path = "/a")
public JsonResult add(Book book) {
String imageJson= URLDecoder.decode(book.getImage(),"utf-8" );
return null;
}

解码前:后端接收到的book.getImage()就是前端转码后的样子:

%22/images/ac57249167ce4af5.jpg%22%7D,%22/images/9d7bf84bdf40e030.jpg%22%7D%5D

解码后:

["/images/ac57249167ce4af5.jpg","/images/9d7bf84bdf40e030.jpg"]

参考:java-encodeURI decodeURI 解决地址传参乱码问题

【SpringBoot】No 'Access-Control-Allow-Origin' header is present on the requested resource.的更多相关文章

  1. .Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

    网页请求报错: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Or ...

  2. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    前端显示: has been blocked by CORS policy: Response to preflight request doesn't pass access control che ...

  3. WCF REST开启Cors 解决 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.

    现象: 编写了REST接口: [ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(UriTemp ...

  4. Failed to load http://wantTOgo.com/get_sts_token/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fromHere.com' is therefore not allowed access.

    Failed to load http://wantTOgo.com/get_sts_token/: No 'Access-Control-Allow-Origin' header is presen ...

  5. java、ajax 跨域请求解决方案('Access-Control-Allow-Origin' header is present on the requested resource. Origin '请求源' is therefore not allowed access.)

      1.情景展示 ajax调取java服务器请求报错 报错信息如下: 'Access-Control-Allow-Origin' header is present on the requested ...

  6. 跨域问题解决----NO 'Access-Control-Allow-Origin' header is present on the requested resource.Origin'http://localhost:11000' is therfore not allowed access'

    NO 'Access-Control-Allow-Origin' header is present on the requested resource.Origin'http://localhost ...

  7. 【MongoDB】The Access control of mongodb

    In this blog we mainly talk about the access control including limitation of ip, setting listen port ...

  8. 【HTTP】HTTP access control (CORS)

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS Cross-site HTTP requests are H ...

  9. Access to XMLHttpRequest at 'http://localhost:8090/user/getotp' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

    ajax跨域请求错误 解决: springboot中: 加注解 @CrossOrigin

随机推荐

  1. Linux服务器---论坛discuz

    Discus Discuz是一款免费的论坛管理系统,大量的使用了AJAX,内部有丰富的模板风格. 1.下载discuz软件(https://cn.wordpress.org/download/rele ...

  2. 【编程思想】【设计模式】【创建模式creational 】工厂模式factory_method

    Python版 https://github.com/faif/python-patterns/blob/master/creational/factory_method.py #!/usr/bin/ ...

  3. 基于docker 操作mysql5.7

    1. 安装好 docker 2. 拉取 mysql5.7 镜像: docker pull mysql:5.7 其他版本 mysql:https://hub.docker.com/_/mysql?tab ...

  4. sqlserver 删除表分区

    我们都知道,SQL server2008R2企业版以及一些其它的版本支持分区函数,当你在这些数据库备份后想在一些不支持分区函数的数据库做还原时,就会失败. 下面我们来解决这个问题. 1.备份数据库!备 ...

  5. 1.Java语言基础

    一:java语言介绍 (1). 1991年出现,1995年5月正式发布 出生地:SUN  创始人:James Gosling  2009年4月被Oracle收购 目前最新的版本2018年3月v10.0 ...

  6. 【力扣】123. 买卖股票的最佳时机 III

    给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格. 设计一个算法来计算你所能获取的最大利润.你最多可以完成 两笔 交易. 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的 ...

  7. 【科研】科研【合同】盖章流程/横向&#183;非涉密/电子科技大学

    [前置手续] 一.在科研管理系统里填单子,立项. 二.科研管理系统审核通过后,对于对面给好的合同,在合同系统里选择[合同业务发起-发起非标准合同],填单子. 三.会有一系列的审核,审核完成后打印合同备 ...

  8. Docker从入门到精通(五)——Dockerfile

    Dockerfile 简单来说就是一个包含用于组合镜像的命令的文本文档,Docker 通过读取 Dockerfile 中的指令就可以按步骤生成镜像,那么在制作镜像之前,我们先了解一下镜像的原理. 1. ...

  9. Docker从入门到精通(七)——容器数据共享

    什么是容器数据共享?简单来说就是容器与容器之间数据共享,容器与宿主机数据共享. 1.为什么需要数据共享? ①.数据持久化 比如我们有一个MySQL集群,通过容器启动,那么项目运行过程中的数据是保存在容 ...

  10. CF1581B Diameter of Graph 题解

    Content \(\textsf{CQXYM}\) 想要构造一个包含 \(n\) 个点和 \(m\) 条边的无向连通图,并且他希望这个图满足下列条件: 该图中不存在重边和自环.也就是说,一条边应该连 ...