Can't specify headers in request in AngularJS - javascript

I have 2 parts in my app - Angular frontend and rails server. And because it's different domains, requests doesn't work by default. There are a lot of staff about that, including stack, but it doesn't works for me.
This is my method in angular controller:
$scope.test =->
# transform = (data) ->
# $.param data
$http.post('http://localhost:3000/session/create', 'token=some',
headers:
'Access-Control-Allow-Origin': 'http://localhost:9000',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
# transformRequest: transform
).success (responseData) ->
console.log(responseData)
I commented transform data, there is no difference in server response.
And I configured app (saw this in some post) like that:
.config ["$httpProvider", ($httpProvider) ->
$httpProvider.defaults.useXDomain = true
delete $httpProvider.defaults.headers.common["X-Requested-With"]
]
I guess that makes request not ajax like (but i'm not sure).
But there is no headers in my request. They all in some field Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type:
Request URL:http://localhost:3000/session/create
Request Method:OPTIONS
Status Code:404 Not Found
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,ru;q=0.6
Access-Control-Request-Headers:access-control-allow-origin, accept, access-control-allow-headers, access-control-allow-methods, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
DNT:1
Host:localhost:3000
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.8 Safari/537.36
Response Headers
Content-Length:12365
Content-Type:text/html; charset=utf-8
X-Request-Id:2cf4b37b-eb47-432a-ab30-b802b3e33218
X-Runtime:0.030128
Chrome console:
OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730
OPTIONS http://localhost:3000/session/create No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. angular.js:6730
XMLHttpRequest cannot load http://localhost:3000/session/create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. localhost/:1
Other insignificant information:
On the server:
class ApplicationController < ActionController::Base
before_filter :allow_cross_domain_access
protected
def allow_cross_domain_access
headers['Access-Control-Allow-Origin'] = '*'# http://localhost:9000
headers['Access-Control-Allow-Headers'] = 'GET, POST, PUT, DELETE'
headers['Access-Control-Allow-Methods'] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
headers['Access-Control-Max-Age'] = '1728000'
end
end
Routes is obvious post "session/create". And session controller:
class SessionController < ApplicationController
respond_to :json, :html, :js
def create
respond_with "logged in"
# render nothing: true
end
end
I use latest version of angular 1.2.0.rc-2. this is my project on github

You mix up the request and response headers in your example.
When doing a cross domain request (CORS) and you want to make anything different than a plain GET - so for example a POST or adding custom headers - the browser will first make an OPTIONS request.
This is what you see in your developer console:
OPTIONS http://localhost:3000/session/create 404 (Not Found) angular.js:6730
The server then should add the appropriate headers to the response of the OPTIONS request.
So you can remove the custom headers from the Angular call.
Next you need to make sure that your server/application answers the OPTIONS request, not returning a 404.

Related

Access-Control-Allow-Originin multiple values with AJAX to PHP on Remote URL (same server)

I know there are a ton of similar posts about this subject, but I have been at this almost full time for two days and tried & read about any possible solution i could find. None worked so I am trying to figure out if any other expert has an idea that might work.
I'm trying to call a PHP script on (fictional) websiteshop.net from websitedojo.com. It's done with an AJAX call and works fine on the native URL.
I'm transferring the program, but want to leave the backend scripts on the native/original URL. I'm getting the error that is well known and widely diuscussed:
Failed to load https://websiteshop.net/cl/ajax-tst.php: The
'Access-Control-Allow-Origin' header contains multiple values
'https://websitedojo.com, *', but only one is allowed. Origin
'https://websitedojo.com' is therefore not allowed access.
Plus, after clikcing the alert box:
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://websiteshop.net/cl/ajax-tst.php with MIME type
application/json. See
https://www.chromestatus.com/feature/5629709824032768 for more
details.
I have tested so many things by now it is driving me insane. Below the part of an AJAX call, I tried all sorts of variations and combinations here. Whatever is commented, I tried as well without comments of course:
AJAX:
$.ajax({
url: "https://websiteshop.net/cl/ajax_tst.php", // Url to which the request is send
// headers:{
// "Access-Control-Allow-Origin": "*"
// },
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
//data: data,
crossOrigin: true,
dataType: 'jsonp',
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
...
In htaccess I tried all combinations like these and others:
Options -Indexes
Header set Access-Control-Allow-Origin "https://websitedojo.com, *"
#<IfModule mod_headers.c>
# SetEnvIf Origin "http(s)?://(www\.)?(websitedojo.com|other.nl)$" AccessControlAllowOrigin=$0$1
# Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
# Header set Access-Control-Allow-Credentials true
#</IfModule>
In the PHP file itself, I tried these combinations (also without https://):
header_remove('Access-Control-Allow-Origin');
// header('Access-Control-Allow-Origin: "https://websitedojo.com, *');
$allowed=array('https://websitedojo.com','https://www.websitedojo.com', 'https://websiteshop.net','http://localhost','http://127.0.0.1');
$origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:$_SERVER['HTTP_HOST'];
if(in_array($origin, $allowed)){
header('Access-Control-Allow-Origin: '.$origin);
}else{
exit(0);
}
header('Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With');
header('P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"');
header('Access-Control-Max-Age: 1');
This is the latest result from the headers.
Requestheaders:
Host: websiteshop.net
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: */*
Accept-Language: nl,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Referer: https://websitedojo.com/websiteshop/dynamic-and-crazy-engagement/
Content-Type: multipart/form-data; boundary=---------------------------23129260416654
Content-Length: 297094
Origin: https://websitedojo.com
Connection: keep-alive
Response:
HTTP/1.1 200 OK
Server: nginx
Date: Tue, 16 Oct 2018 10:53:37 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.6.37
Access-Control-Allow-Origin: https://websitedojo.com
Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Authorization, X-Requested-With
P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"
Access-Control-Max-Age: 1
Vary: User-Agent
Access-Control-Allow-Origin: *
Content-Encoding: gzip
Are there any none-server related things I can try? Or can I run an SSH command to see my serversettings for the necessary settings?
Ok, solved (with new issues but that's fine).
Apache and Nginx were each setting the same header, my host (thanks Mike) has removed the one from apache so only nginx is setting it now.

No 'Access-Control-Allow-Origin' header with ExpressJS to local server

I know that this subject seems to be already answered many time but i really don't understand it.
I have an local angular-fullstack app (Express, NodeJs) which has his
server A (localhost:9000/).
i have an another local front app B (BlurAdmin done with
generator-gulp-angular) (localhost:3000/)
My server A was autogenerate with Express and Nodejs:
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', false);
next();
});
In my app B, a GET request to my API of serveur A works
$http.get('http://localhost:9000/api/shows')
But with a PUT request:
$http.put('http://localhost:9000/api/shows/1', object)
i have the following error:
XMLHttpRequest cannot load http://localhost:9000/api/shows/1. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. The response had HTTP status code 403.
I try with:
$http({
method: "PUT",
url:'http://localhost:9000/api/shows/1',
headers: {
'Content-type': 'application/json'
},
data:object
});
Not working,
I try with:
res.header('Access-Control-Allow-Origin', '*');
Not working,
I have installed *ExtensionAllow-Control-Allow-Origin: ** for chrome and that has done nothing (that return just not all the code but only error 403 (forbidden)
I don't really know why this is not working for PUT when it's working with GET.
Have you already had this problem? Thanks!
Updated:1 The result in my Browser:
for GET
General:
Request URL:http://localhost:9000/api/shows/1
Request Method:OPTIONS
Status Code:200 OK
Request header:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de-DE;q=0.2,de;q=0.2
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:PUT
Connection:keep-alive
Host:localhost:9000
Origin:http://localhost:3000
Referer:http://localhost:3000/
Response header:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With,content-type
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin:http://localhost:3000
Allow:GET,HEAD,PUT,PATCH,DELETE
Connection:keep-alive
Content-Length:25
Content-Type:text/html; charset=utf-8
For PUT request:
general:
Request URL:http://localhost:9000/api/shows/1
Request Method:PUT
Status Code:403 Forbidden
Response Header:
Connection:keep-alive
Content-Encoding:gzip
Content-Type:application/json; charset=utf-8
Date:Thu, 25 Aug 2016 16:29:44 GMT
set-cookie:connect.sid=s%3AsVwxxbO-rwLH-1IBZdFzZK1xTStkDUdw.xuvw41CVkFCRK2lHNlowAP9vYMUwoRfHtc4KiLqwlJk; Path=/; HttpOnly
set-cookie:XSRF-TOKEN=toaMLibU5zWu2CK19Dfi5W0k4k%2Fz7PYY%2B9Yeo%3D; Path=/
Strict-Transport-Security:max-age=31536000; includeSubDomains; preload
Request header:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4,de-DE;q=0.2,de;q=0.2
Connection:keep-alive
Content-Length:27
Content-Type:application/json
Host:localhost:9000
Origin:http://localhost:3000
Referer:http://localhost:3000/
Request Payload:
{url_name: "myData"}
url_name
:
"myData"
Thanks for helping
Update 2: with https://github.com/troygoode/node-cors-server/blob/master/app.js and the work of #Chris Foster
I have install npm cors --save
in my app.js,
i have now the following code:
import express from 'express';
import cors from 'cors';
var app = express()
var corsOptions = {
origin: 'http://localhost:3000'
}
var issuesoption = {
origin: true,
methods: ['PUT'],
credentials: true,
};
app.use(cors(corsOptions))
app.options('*', cors(issuesoption));
app.put('/api/shows/:id',cors(issuesoption) ,function(req,res){
res.json({
data: 'Issue #2 is fixed.'
});
});
And that is still not working with:
$http.put("http://localhost:9000/api/shows/1",object)
BUT i don't have any 403 error, I have now,
Request URL:http://localhost:9000/api/shows/1
Request Method:PUT
Status Code:200 OK
But that doesn't put the data into the server and i have in Preview:
{data: "Issue #2 is fixed."}
When you make a request that can change something (POST, PUT, etc), CORS rules require that the browser makes a preflight request (OPTIONS) before making the actual request.
In Node, you have to specifically handle these OPTION requests. It's likely you are only handling the PUT (app.put('/etc/etc/')), and the preflight request is failing.
You need to add handling for preflight OPTION requests, but better yet check out the cors package which makes this all much more simple and does it for you:
const express = require('express')
const cors = require('cors')
const app = express()
const corsOptions = {
origin: 'http://example.com'
}
app.use(cors(corsOptions))

AJAX function w/ Mailgun, getting "ERROR Request header field Authorization is not allowed by Access-Control-Allow-Headers"

I'm working on making an AJAX call that hit the Mailgun API to send email. Documentation on Mailgun says that post requests should be made to "https://api.mailgun.net/v3/domain.com/messages". I've included my api key as specified by mailgun (they instruct to use a username of 'api'). Since this involves CORS, I can't get past the error: Request header field Authorization is not allowed by Access-Control-Allow-Headers.
However, I've inspected the requests/responses in the Network tab and "Access-Control-Allow-Origin" in the response from Mailgun is set to "*"...which should indicate that it should allow it? (See request/response below): I've edited the actual domain and my API key.
Remote Address:104.130.177.23:443
Request URL:https://api.mailgun.net/v3/domain.com/messages
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.mailgun.net
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type, x-requested-with
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:600
Allow:POST, OPTIONS
Connection:keep-alive
Content-Length:0
Content-Type:text/html; charset=utf-8
Date:Fri, 20 Mar 2015 19:47:29 GMT
Server:nginx/1.7.9
My code for the ajax call is below, in which I include my credentials in the headers and the domain to where the post is supposed to go. Not sure what's causing this not to work. Is it because I'm testing on local host? I didn't think that would make a difference since the "Access Control Allow Origin:*" in the response header. Any help would be greatly appreciated! Thank you.
function initiateConfirmationEmail(formObj){
var mailgunURL;
mailgunURL = "https://api.mailgun.net/v3/domain.com/messages"
var auth = btoa('api:MYAPIKEYHERE');
$.ajax({
type : 'POST',
cache : false,
headers: {"Authorization": "Basic " + auth},
url : mailgunURL,
data : {"from": "emailhere", "to": "recipient", etc},
success : function(data) {
somefunctionhere();
},
error : function(data) {
console.log('Silent failure.');
}
});
return false;
}
Drazisil is correct above. The response needs to include Access-Control-Allow-Headers: Authorization as you are including that header in your request and Authorization is not a simple header.

Backbone & Slim PHP - Access-Control-Allow-Headers - Can GET information, can't POST it?

I'm using Backbone and the Slim PHP framework. I'm trying to post information to my API, however Access-Control-Allow-Headers keeps causing me problems...
My console reads:
OPTIONS http://api.barholla.com/user/auth 405 (Method Not Allowed) zepto.min.js:2
XMLHttpRequest cannot load http://api.barholla.com/user/auth. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
My headers read:
Request URL:http://api.barholla.com/user/auth
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, content-type, accept
Access-Control-Request-Method:POST
Connection:keep-alive
Host:api.barholla.com
Origin:http://localhost
Referer:http://localhost/barholla/app/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4
Response Headersview source
Access-Control-Allow-Origin:*
Allow:POST
Connection:close
Content-Type:application/json
Date:Thu, 08 Nov 2012 16:12:32 GMT
Server:Apache
Transfer-Encoding:chunked
X-Powered-By:Slim
X-Powered-By:PleskLin
My headers in my slim index.php file are:
$res = $app->response();
$res->header('Access-Control-Allow-Origin', '*');
$res->header("Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS");
To handle the post data:
$app->post('/user/auth', function () use ($app) {
//code here
});
In my javascript (i'm using the backbone framework) my code is:
App.userAuth = new App.UserAuthModel({
username: $('#username').val(),
password: hex_md5($('#password').val())
});
App.userAuth.save({}, {
success: function(model, resp) {
console.log(resp);
},
error: function(model, response) {
console.log(response);
}
});
Any help would be much appreciated, I've been stuck on this for ages!
I had a similar cross domain POST problem (in fact with all headers except GET). The following resolved it:
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && (
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST' ||
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'DELETE' ||
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'PUT' )) {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT'); // http://stackoverflow.com/a/7605119/578667
header('Access-Control-Max-Age: 86400');
}
exit;
}
In your javascript client you're making an OPTIONS request to /user/auth, but in your PHP code you're only accepting POST requests through this endpoint.
If you want your API to accept OPTIONS method you should have something like this in your code:
$app->options('/user/auth', function () use ($app) {
//code here
});
Or, if you want to handle multiple HTTP methods in the same function:
$app->map('/user/auth', function () use ($app) {
if ($app->request()->isOptions()) {
//handle options method
}
else if ($app->request()->isPost()) {
//handle post method
}
})->via('POST', 'OPTIONS');
Keep in mind that the OPTIONS method, according to W3C:
[...] represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
Alternatively, just change your client's code to make a POST request instead of OPTIONS request. It's easier and makes more sense than authenticating a user through the OPTIONS method. In zepto.js it would be something like this:
$.post('/user/auth', { foo: 'bar' }, function(response){
console.log(response);
});
Your OPTIONS request should be a 200 returning an empty response. Then the browser will send the real POST request.
Also no need to add OPTIONS in Access-Control-Allow-Methods header.
It seems your using authentication, why not add Access-Control-Allow-Credentials header too.
For more informations check this code it may be helpful.
CorsSlim helped me. https://github.com/palanik/CorsSlim
<?php
$app = new \Slim\Slim();
$corsOptions = array("origin" => "*",
"exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
"allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'));
$cors = new \CorsSlim\CorsSlim($corsOptions);
$app->add($cors);

Only GET working in cross domain API request with django-piston

I'm not able to do POST/PUT/DELETE cross-domain request on my API using django-piston, I've CORS enabled using this script (based on this):
class CORSResource(Resource):
"""
Piston Resource to enable CORS.
"""
# headers sent in all responses
cors_headers = [
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Headers', 'AUTHORIZATION'),
]
# headers sent in pre-flight responses
preflight_headers = cors_headers + [
('Access-Control-Allow-Methods', '*'),
('Access-Control-Allow-Credentials','true')
]
def __init__(self, handler, authentication=None):
super(CORSResource, self).__init__(handler, authentication)
self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)
def __call__(self, request, *args, **kwargs):
request_method = request.method.upper()
# intercept OPTIONS method requests
if request_method == "OPTIONS":
# preflight requests don't need a body, just headers
resp = HttpResponse()
# add headers to the empty response
for hk, hv in self.preflight_headers:
resp[hk] = hv
else:
# otherwise, behave as if we called the base Resource
resp = super(CORSResource, self).__call__(request, *args, **kwargs)
# slip in the headers after we get the response
# from the handler
for hk, hv in self.cors_headers:
resp[hk] = hv
return resp
#property
def __name__(self):
return self.__class__.__name__
In the frontend I'm using Backbone with JSONP activated. I don't have any errors, the OPTIONS request works fine then nothing happens. I tried to change the « Access-Control-Allow-Methods » but it doesn't change anything. Any idea ?
Edit:
Here is the request headers of an OPTIONS request:
OPTIONS /api/comments/ HTTP/1.1
Host: apitest.dev:8000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Origin: http://3l-oauth.dev:1338
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization,content-type
Pragma: no-cache
Cache-Control: no-cache
and the response headers:
HTTP/1.0 200 OK
Date: Sat, 12 May 2012 09:22:56 GMT
Server: WSGIServer/0.1 Python/2.7.3
Access-Control-Allow-Methods: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: AUTHORIZATION
Content-Type: text/html; charset=utf-8
X-Frame-Options: SAMEORIGIN
JSONP is GET only:
You cannot make POST, PUT, or DELETE requests cross-domain. Cross domain JavaScript is facilitated through the use of <script> tags that send requests to your server for dynamic JavaScript. script tags are GET requests only.
However, one of the recommended methods for adjusting to this limitation when dealing with cross-domain JavaScript is to use a method query parameter that you would use in your server-side code to determine how you should handle a specific request.
For instance, if the request was
POST /api/comments/
then you could do this:
/api/comments?method=POST
Under the hood, it's still a GET request, but you can achieve your goal with slight modifications to your API.
When determining the type of request, instead of checking the HTTP Method:
if request_method == "OPTIONS":
Check the request parameter "method" instead:
if request.GET["method"] == "OPTIONS":
JSONP Requests Must return JavaScript:
The other really important point to take note of is that your JSONP requests must all return JavaScript wrapped (or padded) in a function call. Since the requests are made under the hood by script tags that expect JavaScript, your server must return content that the browser understands.
If this doesn't make sense to you or you need more information, there is a great explanation here on how JSONP and script tag remoting works under the hood.

Categories

Resources