使用application / json contentType的AJAX POST调用获得“no”Access-Control-Allow-Origin'标题"错误 [英] AJAX POST call with application/json contentType gets "no 'Access-Control-Allow-Origin' header" error

查看:365
本文介绍了使用application / json contentType的AJAX POST调用获得“no”Access-Control-Allow-Origin'标题"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的Javascript功能。每当我运行它(使用WebView从Android应用程序调用它)时,它将作为 application / x-www-form-urlencoded 发送,尽管 dataType:json属性。

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 having the dataType: "json" attribute.

如果我添加 contentType:application / json; charset = utf- 8然后甚至没有收到服务器的请求,我收到错误:

If I add contentType: "application/json; charset=utf-8" then the request is not even received from the server and I get error:


XMLHttpRequest无法加载< a href =https://example.com/api =nofollow noreferrer> https://example.com/api 。对
预检请求的响应未通过访问控制检查:请求的
资源上没有
'Access-Control-Allow-Origin'标头。因此不允许原点'null'访问。

XMLHttpRequest cannot load https://example.com/api. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

请求标题如下所示:

OPTIONS /api HTTP/1.1
Host: example.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: null
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es;q=0.6

服务器是在Jetty Embedded上运行的Java Servlet,它甚至都没有有一个WEB-INF或web.xml,因为它不是一个Web应用程序,而是一个API。服务器甚至没有收到请求,所以我想这不会通过添加 response.addHeader(Access-Control-Allow-Origin,*);

The server is a Java Servlet running on Jetty Embedded that does not even have a WEB-INF or web.xml as it is not a web app but an API. The server does not even receive the request, so I guess it won't be solved by adding response.addHeader("Access-Control-Allow-Origin", "*");

回复标题:

HTTP/1.1 200 OK
Allow: POST, TRACE, OPTIONS
Content-Length: 0
Server: Jetty(9.0.z-SNAPSHOT)

客户端Javascript

function create(userId, callback) {

  var submitData = {
    "action": "create",
    "userId": userId
  };

  $.ajax({
    data: JSON.stringify(submitData),
    type: "POST",
    url: "https://www.example.com/api",
    dataType: "json"
  })
  .done(function(data) { callback(SUCCESS); })
  .fail(function() { callback(UNKNOWN_ERROR); });
}

编辑:尝试在没有JQuery的情况下执行此请求仍然不起作用。

Tried doing this request without JQuery and still doesn't work.

  var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
  xmlhttp.open("POST", "https://www.example.com/api");
  xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  xmlhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
  xmlhttp.send(JSON.stringify(submitData));


推荐答案

这对我有用(我正在使用 Tomcat ,而不是 Jetty 尽管如此。我没有对 JSON 有效负载做任何事情,只是测试服务器上的URL是否被命中。

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(普通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回调(结果)

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

这篇关于使用application / json contentType的AJAX POST调用获得“no”Access-Control-Allow-Origin'标题&quot;错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆