问题
I'm trying to receive data from SendGrid API
$.ajax({
type:'GET',
url:"https://sendgrid.com/api/bounces.get.json",
data: {api_user:'username',api_key:'userkey',date:1},
success: function(data){
console.log(data)
},
crossDomain: true,
dataType: 'jsonp',
error:function(a,b,c){
console.log(a);
}
});
Console shows:
Object { readyState=4, status=200, statusText="success"}
parsererror
Error: jQuery17208301184673423685_1374648217666 was not called
Where is the bug or issue ?
回答1:
The issue is that SendGrid does not support jsonp.
Unfortunately, switching to plain JSON will not work either, as SendGrid has no CORS headers and browsers will not allow you to access the pages. In short you cannot make AJAX requests dorectly to SendGrid.
However, generally this is for the better as all SendGrid endpoints require authentication and having your username and password in an AJAX request would allow users to take them and then use them to send email.
To get these stats on the frontend, you'll need a server to get them and output them on your domain or a domain with CORS allowances.
回答2:
Here comes a one click solution!
- Deploy your instance of SendGrid Proxy to Heroku
- Use
{your-sendgrid-proxy}.herokuapp.com
instead ofapi.sendgrid.com
- Done (Really)
How it works:
- It creates a node powered http proxy using express-http-proxy
- It adds needed headers such as
Authorization
andContent-Type
- It overrides
Access-Control-Allow-Origin
to*
to make your browserCORS
warning free
See how the magic is working. Feedback is welcome!
来源:https://stackoverflow.com/questions/17827253/sendgrid-api-json-call