UnityWebRequest uploadProgress [duplicate] - android

How can I send HTTP GET and POST requests in C# with Unity?
What I want is:
send json data in post request (I use Unity serializer, so no need in
new one, I just want to pass string in post data and have ability to
set ContentType to application/json);
get response code and body without any problems;
do it all asynchronous without blocking ui rendering.
What I've tried:
implementing with HttpWebRequest/HttpWebResponse, but it's too hard and low level (if I won't found anything better, I'll have to use it);
using unity WWW, but it doesn't match my requirements;
using some external packages from NuGet - Unity don't accept them :(
Most problems were with threading, I'm not experienced enough in it in C#.
IDE, I use, is Intellij Rider.

The WWW API should get this done but UnityWebRequest replaced it so I will answer the newer API. It's really simple. You have to use coroutine to do this with Unity's API otherwise you have have to use one of C# standard web request API and Thread. With coroutine you can yield the request until it is done. This will not block the main Thread or prevent other scripts from running.
Note:
For the examples below, if you are using anything below Unity 2017.2, replace SendWebRequest() with Send() and then replace isNetworkError with isError. This will then work for the lower version of Unity. Also, if you need to access the downloaded data in a binary form instead, replace uwr.downloadHandler.text with uwr.downloadHandler.data. Finally, the SetRequestHeader function is used to set the header of the request.
GET request:
void Start()
{
StartCoroutine(getRequest("http:///www.yoururl.com"));
}
IEnumerator getRequest(string uri)
{
UnityWebRequest uwr = UnityWebRequest.Get(uri);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
POST request with Form:
void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com"));
}
IEnumerator postRequest(string url)
{
WWWForm form = new WWWForm();
form.AddField("myField", "myData");
form.AddField("Game Name", "Mario Kart");
UnityWebRequest uwr = UnityWebRequest.Post(url, form);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
POST request with Json:
void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com", "your json"));
}
IEnumerator postRequest(string url, string json)
{
var uwr = new UnityWebRequest(url, "POST");
byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
uwr.SetRequestHeader("Content-Type", "application/json");
//Send the request then wait here until it returns
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
POST request with Multipart FormData/Multipart Form File:
void Start()
{
StartCoroutine(postRequest("http:///www.yoururl.com"));
}
IEnumerator postRequest(string url)
{
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormDataSection("field1=foo&field2=bar"));
formData.Add(new MultipartFormFileSection("my file data", "myfile.txt"));
UnityWebRequest uwr = UnityWebRequest.Post(url, formData);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
PUT request:
void Start()
{
StartCoroutine(putRequest("http:///www.yoururl.com"));
}
IEnumerator putRequest(string url)
{
byte[] dataToPut = System.Text.Encoding.UTF8.GetBytes("Hello, This is a test");
UnityWebRequest uwr = UnityWebRequest.Put(url, dataToPut);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
}
DELETE request:
void Start()
{
StartCoroutine(deleteRequest("http:///www.yoururl.com"));
}
IEnumerator deleteRequest(string url)
{
UnityWebRequest uwr = UnityWebRequest.Delete(url);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Deleted");
}
}

Use HttpClient and something like:
public static HttpContent DoPost(object payload, string subPath)
{
var httpClient = new HttpClient();
HttpClient.BaseAddress = new Uri(Global.BaseUrl);
HttpClient.DefaultRequestHeaders.Clear();
HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // if you're using json service
// make request
var response = Global.HttpClient.PostAsJsonAsync(subPath.TrimLeadingSlash(), payload).Result;
// check for error
response.EnsureSuccessStatusCode();
// return result
return response.Content;
}
Payload is an object to be serialized to json. If all requests are going to the same baseUrl, you can set up HttpClient globally, and reuse it here

https://www.patrykgalach.com/2019/04/18/how-to-call-rest-api-in-unity/
Please refer this link cleanest way to play with data
and do not use www instead of use UnityWebRequest

We can use WWW and UnityWebRequest classes to initiate API calls. WWW got obsolete now and Unity recommends using UnityWebRequest over WWW.
void Start() {
string url = "https://retrofit-backend-demo.herokuapp.com/book";
StartCoroutine(GetBooksUsingWWW(url));
StartCoroutine(GetBooksUsingUnityWebRequest(url));
}
IEnumerator GetBooksUsingWWW(string url) {
using (WWW www = new WWW(url)){
yield return www;
Debug.Log(www.text);
JSONNode jsonNode = JSON.Parse(www.text);
string title = jsonNode[0]["title"].ToString();
Debug.Log("Title: " + title);
}
}
IEnumerator GetBooksUsingUnityWebRequest(string url) {
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
Debug.Log(www.downloadHandler.text);
JSONNode jsonNode = JSON.Parse(www.downloadHandler.text);
string title = jsonNode[0]["title"].ToString();
Debug.Log("Title: " + title);
}
}
For demo: https://github.com/codemaker2015/api-interaction-unity3d-demo

Related

How should we chain the work request with the input data in android work manager?

I am trying to learn work manager chaining with passing output of one to another
Here are my objectives,
I have two work request WR1 (gets me the url) and WR2 (sends request to the url)
I can't and should not start the WR2 until the WR1 completes.
WR1 is supposed to return a url to which i have to send to WR2 as inputData
I can mostly do this without chaining. But i would to like explore it in the chaining.
Here is my snippet in progress. Please help.
WorkManager mWorkManager = WorkManager.getInstance(this);
//WR1
OneTimeWorkRequest urlRequest = new
OneTimeWorkRequest.Builder(UriResolveWorker.class).build();
//WR2
OneTimeWorkRequest pullRequest = new
OneTimeWorkRequest.Builder(PullReplicator.class).build();
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mWorkManager.beginWith(urlRequest)
.then(pullRequest) // I should be able to pass the result of urlRequest.
.enqueue();
}
});
mWorkManager.getWorkInfoByIdLiveData(urlRequest.getId()).observe(this, new
Observer<WorkInfo>() {
#Override
public void onChanged(WorkInfo workInfo) {
if (workInfo != null) {
WorkInfo.State state = workInfo.getState();
// I will get the URL here and i want to pass this to WR2
message = workInfo.getOutputData().getString("work_result");
tvStatus.append("\n"+"state : "+state.toString() + "message : " +message + "\n");
}
}
});
mWorkManager.getWorkInfoByIdLiveData(pullRequest.getId()).observe(this, new Observer<WorkInfo>() {
#Override
public void onChanged(WorkInfo workInfo) {
if (workInfo != null) {
WorkInfo.State state = workInfo.getState();
String count = workInfo.getOutputData().getString("work_result");
tvStatus.append("\n"+"state : "+state.toString() + " No of Documents : " +count + "\n");o
}
}
});
Before returning the Result object in doWork() method of UriResolveWorker class, You can pass the url to Result.success().
First create object of Data.Builder() and then put the url into:
Data.Builder outputDataBuilder = Data.Builder();
outputDataBuilder.putString(KEY_URL_STRING, url.toString());
after that, create Data object with outputDataBuilder:
Data outputData = outputDataBuilder.build();
now you can return the Result with outputData :
return Result.success(outputData);
Workmanager sends the data to pullRequest when the first one has been done.
Please check the state of the WorkRequest before getting the data.
For example:
private final Observer<WorkInfo> urlWorkInfo = workInfo -> {
if (workInfo == null) {
return;
}
WorkInfo.State state = workInfo.getState();
if (state.isFinished()) {
String url = workInfo.getOutputData()
.getString(KEY_URL)
if (url != null) {
Log.d(TAG_MAIN_ACTIVITY, url);
} else {
Log.d(TAG_MAIN_ACTIVITY, "Url not found!");
}
} else if (state == WorkInfo.State.RUNNING) {
Log.d(TAG_MAIN_ACTIVITY, "Associated WorkRequest is being executed");
}
};
I know it's been a while since you asked this question, but maybe it might help someone in the feature:
In WR1 (Worker 1) you will have output with specific key - data that you want in your second worker (WR2):
Result.success(workDataOf(MY_TEST_KEY to someData.toString()))
Now if you want to get that data in WR2 you cannot send it trough setInputData() method when creating your OneTimeWorkRequest and chaining it.
As everything is forwarded from WR1 to WR2, in WR2 you have to fetch that data like:
inputData.getString(WR1.MY_TEST_KEY)
And than use it as you want in your WR2.
Hopefully this will help someone in the future, official documentation can be found here: https://developer.android.com/topic/libraries/architecture/workmanager/how-to/chain-work

Android Retrofit Request Using AWS Signature Authorization

I'm trying to get data from the API which needs to handle aws-authentication, my question is how can I generate Authorization and X-Amz-Date?
I have to pass 3 parameter as header: Content-Type, Authorization and X-Amz-Date.
As you can find in image:
here is the function that generate Authorization String:
public static String gerateOAuthAWS(Context co) throws Exception {
JodaTimeAndroid.init(co);
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").withLocale(Locale.US);
String ZONE = "GMT";
DateTime dt = new DateTime();
DateTime dtLondon = dt.withZone(DateTimeZone.forID(ZONE)).plusHours(1);
String formattedDate = dtLondon.toString(fmt);
String oauth = "AWS4-HMAC-SHA256 Credential="+ ACCESS_KEY+"/us-east-1/execute-api/aws4_request, SignedHeaders=content-type;host;x-amz-date, Signature="+
getSignatureKey(SECRET_KEY,formattedDate,"us-east-1","execute-api");
return oauth;
}
static byte[] HmacSHA256(String data, byte[] key) throws Exception {
String algorithm="HmacSHA256";
Mac mac = Mac.getInstance(algorithm);
mac.init(new SecretKeySpec(key, algorithm));
return mac.doFinal(data.getBytes("UTF8"));
}
static String getSignatureKey(String key, String dateStamp, String regionName, String serviceName) throws Exception {
byte[] kSecret = ("AWS4" + key).getBytes("UTF8");
byte[] kDate = HmacSHA256(dateStamp, kSecret);
byte[] kRegion = HmacSHA256(regionName, kDate);
byte[] kService = HmacSHA256(serviceName, kRegion);
byte[] kSigning = HmacSHA256("aws4_request", kService);
return Base64.encodeToString(kSigning,Base64.DEFAULT).replaceAll("\n", "");
}
Content-Type is "application/x-www-form-urlencoded"
and generate X-Amz-Date something as: "201805138T120046Z"
then pass them through retrofit methods:
#GET("prod/video")
Call<ArrayList<Video>> getAllVideos(#Header("Content-Type")String content_type,
#Header("X-Amz-Date")String amz_date,
#Header("Authorization")String auth);
the result returns null and I'm sure the issue is related the authorization since it worked before well.
thanks for your helps :)
i always said to my friends why do you use retrofit or valley , if it's seems complicated to you !
instead you can use JSOUP or OKHTTP it's much easier and I realy love JSOUP
an example that you can connect and send you data:
private void fcmIdentity(final String fcmKey) {
new Thread(new Runnable() {
#Override
public void run() {
try {
SSLHelper.enableSSLSocket();
Connection.Response response = Jsoup
.connect(Urls.identity)
.header("Accept", "application/json")
.header("KEY_2", "VALUE_2")
.method(Connection.Method.POST)
.ignoreContentType(true)
.ignoreHttpErrors(true)
.validateTLSCertificates(true)
.followRedirects(true)
.data("fcm", "" + fcmKey)
.data("identity", preferences.getString("FCM_ID", ""))
.execute();
Log.i("fcmIdentity", response.statusCode() + "");
Log.i("fcmIdentity", response.toString());
Log.d("fcmIdentity", response.headers().toString());
Log.i("fcmIdentity", response.body());
} catch (Exception e) {
e.printStackTrace();
if (e instanceof IOException) {
G.toast(getString(R.string.connection_error), true);
}
}
}
}).start();
}
about SSLHelper it help to connect to HTTPS
for more info check my topic https://answers.uncox.com/android/question/13003

System.Net.Http.HttpClient with AutomaticDecompression and GetAsync (timeout) vs GetStringAsync (working

I have the following code to make requests to a REST API, using Xamarin and an Android device:
public class ApiBase
{
HttpClient m_HttpClient;
public ApiBase(string baseAddress, string username, string password)
{
if (!baseAddress.EndsWith("/"))
{
baseAddress += "/";
}
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip;
}
m_HttpClient = new HttpClient(handler);
m_HttpClient.BaseAddress = new Uri(baseAddress);
var credentialsString = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
m_HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentialsString);
m_HttpClient.Timeout = new TimeSpan(0, 0, 30);
}
protected async Task<XElement> HttpGetAsync(string method)
{
try
{
HttpResponseMessage response = await m_HttpClient.GetAsync(method);
if (response.IsSuccessStatusCode)
{
// the request was successful, parse the returned string as xml and return the XElement
var xml = await response.Content.ReadAsAsync<XElement>();
return xml;
}
// the request was not successful -> return null
else
{
return null;
}
}
// some exception occured -> return null
catch (Exception)
{
return null;
}
}
}
If i have it like this, the first and the second call to HttpGetAsync work perfectly, but from the 3rd on the GetAsyncstalls and eventually throws an exception due to the timeout. I send these calls consecutively, there are not 2 of them running simultaneously since the results of the previous call are needed to decide the next call.
I tried using the app Packet Capture to look at the requests and responses to find out if i'm sending an incorrect request. But it looks like the request which fails in the end is never even sent.
Through experimentation i found out that everything works fine if don't set the AutomaticDecompression.
It also works fine if i change the HttpGetAsync method to this:
protected async Task<XElement> HttpGetAsync(string method)
{
try
{
// send the request
var response = await m_HttpClient.GetStringAsync(method);
if (string.IsNullOrEmpty(response))
{
return null;
}
var xml = XElement.Parse(response);
return xml;
}
// some exception occured -> return null
catch (Exception)
{
return null;
}
}
So basically using i'm m_HttpClient.GetStringAsync instead of m_HttpClient.GetAsync and then change the fluff around it to work with the different return type. If i do it like this, everything works without any problems.
Does anyone have an idea why GetAsync doesn't work properly (doesn't seem to send the 3rd request) with AutomaticDecompression, where as GetStringAsync works flawlessly?
There are bug reports about this exact issue:
https://bugzilla.xamarin.com/show_bug.cgi?id=21477
The bug is marked as RESOLVED FIXED and the recomended action is to update to the latest stable build. But there are other (newer) bugreports that indicate the same thing that are still open, ex:
https://bugzilla.xamarin.com/show_bug.cgi?id=34747
I made a workaround by implementing my own HttpHandler like so:
public class DecompressionHttpClientHandler : HttpClientHandler
{
protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Headers.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
var msg = await base.SendAsync(request, cancellationToken);
if (msg.Content.Headers.ContentEncoding.Contains("gzip"))
{
var compressedStream = await msg.Content.ReadAsStreamAsync();
var uncompresedStream = new System.IO.Compression.GZipStream(compressedStream, System.IO.Compression.CompressionMode.Decompress);
msg.Content = new StreamContent(uncompresedStream);
}
return msg;
}
}
Note that the code above is just an example and not a final solution. For example the request will not be compressed and all headers will be striped from the result. But you get the idea.

Image uploading Android + Sails.js

What are the possible ways/libraries available to upload images from android app to sails.js Node.js server?
One way that I came across to achieve this is sending Base64 encoded Bitmap image string from the app and saving it to the database, but this seems to be an inefficient way to handle multiple big size images as Base64 encoded string is 33% larger than raw size.
Another way is to send images as multipart form data, but I couldn't found good examples on this. Please, provide examples which demonstrate how to send images from app and handle it at serverside (node.js/sails.js)
Are there any other recommended libraries available to handle image uploading in android?
I use Multer to handle file uploads via multipart form data.
Out of the box it can do memory and disk storage. By using plugin modules you can use Multer to send files direct to S3 or other storage providers.
For backend level, use this piece of code in your SailsJS application:
uploadPhoto: function (req, res) {
req.file('photo').upload({
adapter: require('skipper-s3'),
key: S3_KEY,
secret: S3_SECRET,
bucket: IMAGE_BUCKET_NAME,
dirname: DIRECTORY_NAME,
region: S3_REGION
}, function (err, uploaded) {
if(err) {
//Image not uploaded
//Returned with error
} else if(uploaded.length == 0) {
//Image not uploaded
} else {
//Image uploaded
//Returned Image Path
var imagePath = uploaded[0].extra.Location;
}
});
},
And you need to send the file using multipart request. I am doing it with retrofit library. Here is the android code:
1. Create Multipart RequestBody Object
RequestBody file =
RequestBody.create(MediaType.parse("multipart/form-data"), photo); //photo is of type "File"
2. Handling RequestBody in Interface
#Multipart
#POST("api/uploadphoto")
Call<ResponseBody> uploadPhoto(#Part("photo\"; filename=\"pp\"") RequestBody file);
3. Then initiating the call to server
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response, Retrofit retrofit) {
Log.e("RESPONSE", response.body());
}
}
#Override
public void onFailure(Throwable t) {
Log.e("UploadPhoto", "failed");
}
});
That will upload the image to S3-Bucket.
Sails.js Backend file upload code and file will be uploaded in assets/images folder
upload: function (req, res) {
if (req.method === 'GET')
return res.json({
'status': 'GET not allowed'
});
// Call to /upload via GET is error
var data = req.file('uploadFile');
data.upload({
dirname: '../../assets/images'
}, function onUploadComplete(err, files) {
// Earlier it was ./assets/images .. Changed to ../../assets/images
// Files will be uploaded to ./assets/images
// Access it via localhost:1337/images/file-name
console.log(files);
if (err) {
console.log(err);
return res.json(500, err);
} else if (files.length === 0) {
// proceed without files
res.notFound({
status: 'Unsucess',
response: 'File not Uploaded'
});
} else {
// handle uploaded file
res.json({
status: 200,
file: files
});
}
});
}
Android Code :-
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("fileUploadType", "1")
.addFormDataPart("miniType", contentType)
.addFormDataPart("ext", file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf(".")))
.addFormDataPart("fileTypeName", "img")
.addFormDataPart("clientFilePath", selectedImageUri.getPath())
.addFormDataPart("filedata", filename + ".png", fileBody)
.build();
Request request = new Request.Builder()
.url(API_URL)
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
et_response.setText(e.getMessage());
Toast.makeText(MainActivity.this, "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
et_response.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "response: " + response, Toast.LENGTH_LONG).show();
}
});
}
});
For Android Code You can Refer to
http://blog.aimanbaharum.com/2016/03/26/android-image-multi-part-upload/

Cordova Android emulator app not invoking http POST method to the RESTful php server?

I am developing android app using cordova on Ubuntu 14. Its a hybrid app that consists of:-
Server- RESTful api using Php with slim framework &
Client - Backbone with requirejs,jquery,bootstrap etc.., HTML,CSS.
I have created the app as per the steps given in Apache Cordova Documentation guide (http://cordova.apache.org/docs/en/5.0.0/guide_platforms_android_index.md.html#Android%20Platform%20Guide) and imported the app in android studio. I am using android studio 1.3.
I have connected the app to my localhost using(10.0.2.2), the app runs on the emulator and shows the 'login' screen.
The challange is, after filling user name and password, when I click 'Sign In' it should trigger http 'POST' as in Browser app. But it does not triggers POST and in return I get 404 error in Backbone.sync-error, and when I saw the server HTTP_METHOD it shows 'GET' !!
I have overriden Backbone.sync method.
This is my 'login.js' file triggering the event
//sigin button click code ...
// ...
signinInfo.set({
email: email,
password: password
});
signinInfo.save(null,{
success: function (data) {
window.localStorage.setItem('uid',signinInfo.attributes.uid);
window.localStorage.setItem('email_id',signinInfo.attributes.email_id);
// redirect the user to the given route
if (data.attributes.status == "1") {
window.location.href = "";
} else {
alert("Incorrect password!");
}
} // success
});
The above 'save' on 'signinInfo' model triggers the Backbone.sync method. Here's the code snippet from models.js that overrides 'Backbone.sync' method:
originalSync = Backbone.sync;
Backbone.sync = function (method, model, options) {
var success = options.success;
var error = options.error;
console.log("Models.js- method: " + method + ", model: " + JSON.stringify(model) + ", options: " + JSON.stringify(options));
options.success = function (model, response, options) {
console.log("Models.js- success, response: " +response );
$('.srLoading').hide();
if (typeof model.redirect == 'undefined') {
success(model, response, options);
} else {
window.location.replace("/");
}
};
options.error = function (model, response, options) {
console.log("Models.js- error:" +JSON.stringify(model) + " response: " + response + "; options: " + JSON.stringify(options));
$('.srLoading').hide();
error(model, response, options);
};
// I have tried to put options for crossDomain here, but its not working
options = options || (options = {});
if (!options.crossDomain) {
options.crossDomain = true;
}
if (!options.xhrFields) {
options.xhrFields = {withCredentials:true};
}
if (method === "read") {
console.log("Models.js- read method!" );
$('.srLoading').show();
options.dataType = "jsonp";
return originalSync.apply(Backbone, arguments);
}
if (method === "create") {
console.log("Models.js- create method!" );
$('.srLoading').show();
options.dataType = "jsonp";
options.contentType = 'application/json';
options.type = 'POST';
//options.data = JSON.stringify(options.data);
return originalSync.apply(Backbone, arguments);
}
if (method === "update") {
$('.srLoading').show();
options.dataType = "jsonp";
return originalSync.apply(Backbone, arguments);
}
if (method === "delete") {
$('.srLoading').show();
options.dataType = "jsonp";
return originalSync.apply(Backbone, arguments);
}
}; //Backbone.sync
Above, method 'create' is called but at server it does not converts to 'POST' request. Instead $_SERVER['REQUEST_METHOD'] shows 'GET'! :(
In my Backbone.sync method I commented [options.dataType = "jsonp";] so that the code looks as follows:
...
if (method === "create") {
console.log("Models.js- create method!" );
$('.srLoading').show();
//options.dataType = "jsonp";
options.contentType = 'application/json';
return originalSync.apply(Backbone, arguments);
}
Now my login sends HTTP POST request to the server!
On cross domain (CORS), backbone with dataType 'jsonp' can only make 'GET' request. So to make other actions we need to send 'json' data.

Categories

Resources