I'm trying to use AJAX to perform a POST:
<script>
$(document).ready(function(){
$.ajax({
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader("x-csrf-token",'oECpabcdefco4DFY+LEbetabcdefgD0REBOzk=')},
crossDomain: true,
url: 'http://0.0.0.0:3040/users/gmail_permission/',
data: ({'gmail':'email@gmail.com','id':'49'}),
});
});
</script>
I get the error
Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers.
But when I use a REST client (to debug/test), the post performs without problem. Why is that? I can't see how x-csrf-token is a problem on a REST client but a problem from my AJAX POST?
See http://enable-cors.org as a good resource about CORS.
Cross-Origin Resource Sharing is how a server (google, in this case) allows other websites to make requests across domains. For example, if a user is logged in to their bank account by default, you do NOT want any website to make an ajax GET request to bank.com and see what the user sees. Servers enable CORS as a benefit, so APIs are public and free.
However, those servers (e.g., google api) only allow a subset of headers to go through. See documentation here: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS#Access-Control-Allow-Headers
Google in this case has chosen to disallow "x-csrf-token" in a browser-based ajax call.
It looks like this API is not meant to be called from the client. Also, you are exposing your PRIVATE api key to the user in the browser! Don't do that! This API is meant to be called from the server-side only.
Edit: I see that you are in fact doing an ajax call to your own server, not directly to google. You will need to enable the x-csrf-token access control on your server. Find the server you are using in this list and follow the steps: http://enable-cors.org/server.html
In .htaccess check to allow X-CSRF-Token in headers. Something like this:
Header add Access-Control-Allow-Headers "origin, content-type,X-Requested-With, X-CSRF-Token"