AJAX POST call with application/json contentType gets “no 'Access-Control-Allow-Origin' header” error

前端 未结 1 1746
梦毁少年i
梦毁少年i 2021-01-27 18:04

I have the Javascript function below. Whenever I run it (calling it from an Android app using WebView), it is sent as an application/x-www-form-urlencoded despite h

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-27 18:29

    This works for me (I'm using Tomcat, not Jetty though). I didn't do anything with the JSON payload, just tested if the URL on the server is hit.

    AJAX (plain javascript)

    function issueAjaxPost(){
      var url = "http://localhost:8085/some_url/servlet/PostJson";
      var json = '{ "action": "create", "userId": userId }';
    
      xmlhttp.open("POST", url, true);
      xmlhttp.setRequestHeader("Content-type", "application/json");
      xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
      xmlhttp.send(json);
    }
    

    Servlet

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException  {
      String url = request.getRequestURL().toString();
      String page = url.substring(url.lastIndexOf("/"));
    
      ...
    
      if("/PostJson".equals(page)){
        response.setContentLength("success".length());
        response.setContentType("text/plain");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().write("success");
      }
    }
    

    AJAX callback (the result)

    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("txt2").innerHTML = this.responseText;      //the result (success)
      }
    };
    

    0 讨论(0)
提交回复
热议问题