1. 程式人生 > 實用技巧 >CORS(伺服器端技術)

CORS(伺服器端技術)

CORS跨域訪問說明

2.1CORS說明

CORS,全稱Cross-Origin Resource Sharing [1] ,是一種允許當前域(domain)的資源(比如html/js/web service)被其他域(domain)的指令碼請求訪問的機制,通常由於同域安全策略(the same-origin security policy)瀏覽器會禁止這種跨域請求。
知識回顧:
JSONP: 使用者利用jsonp向伺服器端動態獲取資料的過程. 主體使用者.
CORS: 伺服器是否允許客戶端訪問的技術. 主體伺服器.

2.2 CORS原理說明

使用者可以向普通的ajax請求一樣發起跨域請求. get/post/put/delete,由於當下的跨域的業務比較常見,所有的主流的瀏覽器預設支援跨域. CORS核心需要配置伺服器端是否允許跨域

編輯CORS跨域

說明:為了以後能夠實現通用,則在jt-common中新增cors操作.

package com.jt.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration  //標識我是一個配置類
public class CorsConfig implements WebMvcConfigurer { //擴充套件跨域請求的方法 @Override public void addCorsMappings(CorsRegistry registry) { //1.允許什麼樣的請求進行跨域 // /* 只允許一級目錄請求 /** 表示多級目錄請求. registry.addMapping("/**") //2.允許哪些服務進行跨域 .allowedOrigins("*")
//3.是否允許攜帶cookie資訊 .allowCredentials(true) //4.定義探針檢測時間 在規定的時間內不再詢問是否允許跨域 .maxAge(1800); } }

package com.jt.controller;

import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//伺服器端程式要求返回的都是JSON 所以使用
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /*demo測試*/
    @RequestMapping("/getMsg")
    public String  getMsg(){

        return "sso單點登入系統正常";
    }
}