返回服務器時間的例子:
location /getTime {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET,POST';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
default_type application/json;
return 200 '{\"time\":\"$time_local"}';
}
- time_local
用來記錄訪問時間與時區,實際打印的是日誌產生的時間。 - Access-Control-Allow-Origin
服務器默認是不被允許跨域的。給Nginx服務器配置Access-Control-Allow-Origin *
後,表示服務器可以接受所有的請求源(Origin),即接受所有跨域的請求。 - Access-Control-Allow-Headers 是爲了防止出現以下錯誤:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
這個錯誤表示當前請求Content-Type
的值不被支持。其實是我們發起了"application/json"
的類型請求導致的。 - Access-Control-Allow-Methods 是爲了防止出現以下錯誤:
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.