1 ImportJava.util.HashMap;2 3 ImportOrg.springframework.web.bind.annotation.CrossOrigin;4 Importorg.springframework.web.bind.annotation.RequestMapping;5 ImportOrg.springframework.web.bind.annotation.RequestMethod;6 ImportOrg.springframework.web.bind.annotation.RequestParam;7 ImportOrg.springframework.web.bind.annotation.RestController;8 9 /**Ten * @authorwujing One */ A @RestController -@RequestMapping (value = "/api", method =requestmethod.post) - Public classApicontroller { the -@CrossOrigin (Origins = "http://172.16.71.27:8080") -@RequestMapping (value = "/get") - PublicHashmap<string, object>get (@RequestParam String name) { +hashmap<string, object> map =NewHashmap<string, object>(); -Map.put ("title", "Hello World"); +Map.put ("name", name); A returnmap; at } -}
1<script>2$(function() {3$ (' #title '). Click (function() {4 //alert (' clicked ');5 $.ajax ({6URL: "Http://localhost:8081/api/get",7Type: "POST",8 data: {9Name: "Test"Ten }, OneSuccess:function(data, status, XHR) { A console.log (data); - alert (data.name); - } the }); - }); - }) -</script>
Special attention:
1: Be sure to add a property like method = Requestmethod.post on a class or a method
@RequestMapping (value = "/api", method = requestmethod.post)
2: Add @CrossOrigin Annotations on a method Origins Property Be sure to write the IP number If you enter localhost sometimes 403 errors occur
Eg: @CrossOrigin (origins = "http://172.16.71.27:8080")
POST Http://localhost:8081/api/get 403 ()
Failed to load http://localhost:8081/api/get:No ' Access-control-allow-origin ' header was present on the requested resource . Origin ' http://172.16.71.27:8080 ' is therefore not allowed access. The response had HTTP status code 403.
Change localhost to an IP 172.16.71.27 to access ...
Springboot @crossorigin Annotations Address fine-grained configuration across domains