ajax 跨域 后端解决

来源:互联网 发布:JavaScript post 编辑:程序博客网 时间:2024/06/07 19:59

当通过ajax调用其他服务时,会存在跨域问题,可以通过spring 的一个注解,轻松搞定。

废话不多说,上代码:

package hello;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;/** * Created  on 2017/8/8 0008. */@SpringBootApplication@RestControllerpublic class HelloController {    private static Logger log = LoggerFactory.getLogger(HelloController.class);    //跨域    @CrossOrigin(origins = "http://localhost:63342")    @RequestMapping(value = "/log" , method = RequestMethod.POST)    public void log(String info){        log.info(info);    }    @CrossOrigin(origins = "http://localhost:63342")    @RequestMapping("/hello")    public void hello(){    }    public static void main(String[] args) {        SpringApplication.run(HelloController.class, args);    }}


如上代码所示,是用@CrossOrigin这个注解就可以了。后面的origins的值是里ajax服务的地址。

原创粉丝点击