2016-12-01 104 views
1

我想使用Ajax调用发出POST请求,但是我收到状态码为0的错误,其中所有请求参数都在Advanced REST Client中工作。Javascript Ajax调用不工作?

mycode的:

<button>Post</button> 

$('button').click(function(e) { 
e.preventDefault(); 

$.ajax({ 
     url: "https://api.sendgrid.com/v3/mail/send", 
     type: "POST", 
     contentType : 'application/json', 
     headers : { 
      'Authorization' : 'Bearer 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', 
      'Content-Type' : 'application/json' 
     }, 
     data: JSON.stringify({ 
       "personalizations": [{ 
       "to": [{ 
        "email": "[email protected]" 
       }] 
       }], 
       "from": { 
       "email": "[email protected]" 
       }, 
       "subject": "Great, World!", 
       "content": [{ 
       "type": "text/plain", 
       "value": "Cool OK!" 
       }] 
      }), 
     dataType: "json",   
     success: function (response) { 
      var resp = JSON.parse(response) 
      alert(resp.status); 
     }, 
     error: function (xhr, status) { 
      alert("error : "+status+" :: "+JSON.stringify(xhr)); 
     } 
    }); 
}); 

这是我上面的代码,在运行它不断抛出错误说

{"readyState":0,"responseText":"","status":0,"statusText":"error"}

还要检查在jsfiddle

请帮我,建议我一些解决方案,我无法找到问题我代码。

+0

这是投掷'405方法不允许'请检查你正在发送的参数和服务层的相关方法 – brk

+0

是405但相同的请求参数在高级休息客户端工作正常.. –

+1

我建议使用Fiddler来通过Advance Rest Client发送请求时的样子,以及使用上述代码发送请求时的样子。我认为这是关于CORS的。当您尝试发布到不同的域时,浏览器使用OPTIONS动词发送优先请求,并且对于该请求,您将得到NOT ALLOWED响应(因为服务器不支持此http动词),这就是为什么POST不会工作。 – xxxmatko

回答

2

浏览器扩展并不仅限于浏览器本身的跨源请求。因此,像Advance Rest Client或Postman这样的分机可以请求Cross Origin Resources。 从Chrome浏览器的文章:https://developer.chrome.com/extensions/xhr

因此,当您创建一个想访问另一个域的资源的网站时,您必须启用CORS,就像Matt所说的那样。