1.问题描述:通过Origin,http://localhost:4200请求http://localhost:8081服务,console报如下错误,但是Response为200。客户端和服务器IP相同,但端口不同,并且存在跨域问题。XMLHttpRequest无法加载http://localhost:8081/api/v1/staffs。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许来源'http://localhost:4200'访问.2。解决方法:在服务端/api/v1/staffs的Restful方法中添加@CrossOrigin注解,例如:@CrossOrigin(origins="*",maxAge=3600)@RequestMapping(value="/api/v1/staffs",produces={"application/json"},method=RequestMethod.GET)RestResponseList>queryStaffs(@RequestParam(value="limit",required=false,defaultValue="20")intlimit,@RequestParam(value="offset",required=false,defaultValue="0")intoffset);3、重新发送请求http://localhost:8081/api/v1/...,请求成功。并且响应标头添加了Access-Control-Allow-Credentials和Access-Control-Allow-Origin参数。@CrossOrigin注解将这两个参数添加到响应头中,解决跨域问题。4、服务端POST方法中也使用@CrossOrigin注解解决跨域问题。@CrossOrigin(origins="*",maxAge=3600)@RequestMapping(value="/api/v1/staffs",produces={"application/json"},method=RequestMethod.POST)RestResponse>createStaff(@RequestBodyRestRequest请求);错误如下:5.查看响应码415,错误原因:"status":415,"error":"UnsupportedMediaType","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Contenttype'text/plain;charset=UTF-8'notsupported"6.进一步查看请求头信息,content-type为text/plain。不匹配Content-Type:application/json;charset=UTF-8类型的ResponseHeaders,所以报错。7、指定请求头content-type为application/json,比如在Angular中添加Headers。发送Post请求,请求成功。letheaders=newHeaders({'Content-Type':'application/json'});letoptions=newRequestOptions({headers});returnthis.http.post(this.staffCreateURL,body,options).map((response:Response)=>{//returnthis.http.get(this.userLoginURL).map((response:Response)=>{letresponseInfo=response.json();console.log("====staffCreateURL请求成功返回数据start===");console.log(responseInfo);console.log("====staffCreateURL请求成功返回数据end===");letstaffName=responseInfo.responseInfo.staffName;console.log(staffName);returnresponseInfo;})另外:还可以通过setHeader("Access-Control-Allow-Origin","*")方法给HttpServletResponse对象添加响应头参数解决跨域问题,就是@CrossOrigin注解方式,推荐使用注解,方便。