ajax跨域post提交json字符串报错Request header field Content-Type is not allowed by Access-Control-Allow-Header

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sureSand/article/details/78549929

自己记录一下:ajax post方式提交数据,google浏览器返回状态码为200,但控制台报错:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
ajax代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ajax测试</title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>

$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            type: "POST",
            url: "http://ip:端口/slcServer/slcGlsFlow/reportEvent",
            contentType: "application/json", 
            dataType: "json",
            data: JSON.stringify({"userId":"csqsb02",
    "st_subType":"309002",
    "st_dealType":"300101",
    "st_findDate":"2017-11-10 13:33:56",
    "st_desc":"备注说明ajax-google",
    "problemId":"613",
    "proarea":"12121",
    "reportAddress":"地址",
    "orgsids":"783085",
    "nm_emergency":"50702",
    "lng":"121.534581",
    "lat":"31.239881",
    "areaId":"914",
    "nm_report_mode":"101705"
    }),  
            success: function (jsonResult) {
                alert(jsonResult);
            },
            error:function(jsonResult){
                alert(JSON.stringify(jsonResult));
            }
        });

    });
});
</script>
</head>
<body>

<button>发送一个 HTTP POST 请求页面并获取返回内容</button>

</body>
</html>

原因是我开启了cors跨域,但是设置请求头的时候
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

没有ajax请求中所需的请求类型: contentType: “application/json”。
在cors设置跨域拦截器的时候加上这一类型就好了:

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class SimpleCORSFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin",
                "*");// *号代表全部请求地址
        response.setHeader("Access-Control-Allow-Methods",
                "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");

        response.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");

        response.setHeader("Access-Control-Allow-Credentials","true");

        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}

就是这一句:response.setHeader(“Access-Control-Allow-Headers”, ” Origin, X-Requested-With, Content-Type, Accept”);

阅读更多
换一批

没有更多推荐了,返回首页