前後端傳參1
阿新 • • 發佈:2020-12-08
技術標籤:java
1.前端和後端傳參問題
1.接收Request Payload引數
1)方法2
前端若傳遞Request Payload引數,後端只能用實體類接收,並且要加上註解@RequestBody
2)方法2
public ResTool account(HttpServletRequest request,String userName, String password) {
ServletInputStream is;
try {
is = request.getInputStream();
int nRead = 1;
int nTotalRead = 0;
byte[] bytes = new byte[10240];
while (nRead > 0) {
nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
if (nRead > 0) {
nTotalRead = nTotalRead + nRead;
}
}
// 此處可以接收
String str = new String(bytes, 0, nTotalRead, "utf-8");
return ResTool.build();
} catch (Exception e) {
e.printStackTrace();
}
return ResTool.build();
}
2.跨域解決辦法
關於CORS機制的詳細解釋這裡就不多做介紹了,相關的文件資源也很多,推薦檢視MDN上“ HTTP訪問控制(CORS)”文章的講解。這裡主要記錄一下,我在nginx上做好配置,已經新增好了“Access-Control-Allow-Origin”頭部之後,跨域依舊報錯的問題。
如下是nginx的配置片段,已經加好了相應的頭部:原因在於此介面的返回碼是400,而按照nginx官方文件針對add_header指令的說明,上面的配置,“add_header”指令預設只會給2xx和3xx開頭的部分http返回碼加上頭部,除此返回碼之外的其他響應是不會加上對應頭部的。
location / {
#proxy_pass http://127.0.0.1:9090/;
proxy_pass http://127.0.0.1:8885/;
//把OPTIONS的請求轉成2xx
if ($request_method = 'OPTIONS') {
return 204;
}
add_header "Access-Control-Allow-Origin" "*" always;
add_header "Access-Control-Allow-Credentials" "true" always;
add_header "Access-Control-Allow-Methods" "GET,POST,HEAD,PUT,DELETE,OPTIONS" always;
add_header "Access-Control-Allow-Headers" "access-control-allow-origin, authority, content-type, version-info, X-Requested-With" always;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Request-Proxy-key proxyWS;
proxy_connect_timeout 100;
proxy_send_timeout 100;
proxy_read_timeout 100;
}