Error with HTML5 video in Chrome, using RangeFilePathResult - asp.net-mvc-3

Using MVC3 and flowplayer, I have a video player that is set up to get video files with the following markup:
<div id="video">
<div id="video-viewport">
<!-- The data-ratio is a decimal number represeting the height of the video in proportion to the width -->
<div class="flowplayer" data-swf="http://releases.flowplayer.org/5.1.1/flowplayer.swf"
data-ratio="0.417" data-engine="html5" data-keyboard="true" data-native_ipad_fullscreen="true"
data-volume="0.6">
<video>
<!-- By default Flowplayer attempts to use HTML5 video and if it's not
supported then Flash (9.0+) and MP4 is used. MP4 is enough for
complete browser support but providing WebM and/or OGG gives you
broader support for HTML5 video which is the preferred technology. -->
<!-- MP4 gives a complete cross browser support with the aid of Flash -->
<source type="video/mp4" src="#Url.Action("GetVideo", "Video", new { id = Model.WebMp4Video.Id })"/>
<!-- WEBM gives HTML5 video support for the latest Firefox, Chrome and Opera browser -->
<source type="video/webm" src="#Url.Action("GetVideo", "Video", new { id = Model.WebMVideo.Id })"/>
<!-- OGG gives HTML5 support for older versions of Firefox and Opera -->
<source type="video/ogv" src="#Url.Action("GetVideo", "Video", new { id = Model.OgvVideo.Id })"/>
</video>
</div>
</div>
</div> <!--/video-->
In the controller I have this method returning the videos:
public ActionResult GetVideo(string id) {
...
var cd = new System.Net.Mime.ContentDisposition {
Inline = false
};
FileInfo info = new FileInfo(path);
Response.AppendHeader("Content-Disposition", cd.ToString());
return new RangeFilePathResult(MimeType, info.FullName, info.LastWriteTimeUtc, info.Length);
}
RangeFilePathResult has been a life saver in returning partial responses and this all works fine in Firefox and IE, but in Chrome I am getting a frequent error:
"server cannot set status after http headers have been sent".
and the player itself crashes, revealing the following error on the page:
html5: Video not properly encoded
I am still trying to get my head around partial responses, but could this be because the RangeFileResult sets a status code 206 with each partial response? Or is there anything else I am missing here?
Edit: If I debug through the RangeFileResult code and also inspect the Network tab in Chrome, I notice that the request to the controller method returns the partial response, with status pending, as soon as the code hits this line:
context.HttpContext.Response.Flush();
there seems to be a delay on this, sometimes more than 10 seconds, but when this is complete the status of the repsonse changes to 206. Often while the video is playing, though, the status is again changed to cancelled and this is when the
html5: Video not properly encoded
message appears on the video player.
Edit2: The repsonses I am getting are as follows (3 responses, first and third are cancelled, second has 206 status:
Request
URL: http://localhost:64729/Video/GetVideo/24
Method: GET
Status Code: 206 Partial Content
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:identity;q=1, *;q=0
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:.ASPXAUTH=BD5B9748E6985F5659B56289A5543C11CACBF1602AFFD5D4335453560988B870F2543269809401D13EE9F12EFBAC2D4CE0322B5F826871B9968B3D2986C01E35C536B28B5EC24E8E4F631D094B0DBEFF76DA84DA7CCC753E06C38C0FA36A858AC87548099BD23D4BE9B80434970A542489EC5E5F4543A9C98CA573F196DCBFE1B8CC18C10AE1AFEB0E4E899C6CA4DEFC59138E170954016DCB9C007FDC7C2B2950436E24AA5FF9C0888822626C9AE01C07A98F317A9499F0E9D5E61434F959E9;ASP.NET_SessionId=o112vzki5owvbptr4kudbdax
Host:localhost:64729
Range:bytes=0-
Referer:http://localhost:64729/Video/Index/3
User-Agent:Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Response headers
Cache-Control:private, s-maxage=0
Connection:Close
Content-Length:7362920
Content-Range:bytes 0-7362919/7362920
Content-Type:video/mp4
Date:Tue, 15 Jan 2013 12:55:24 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
Request
URL: http://localhost:64729/Video/GetVideo/24
Method: GET
Status Code: 206 Partial Content
Request headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:identity;q=1, *;q=0
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:.ASPXAUTH=BD5B9748E6985F5659B56289A5543C11CACBF1602AFFD5D4335453560988B870F2543269809401D13EE9F12EFBAC2D4CE0322B5F826871B9968B3D2986C01E35C536B28B5EC24E8E4F631D094B0DBEFF76DA84DA7CCC753E06C38C0FA36A858AC87548099BD23D4BE9B80434970A542489EC5E5F4543A9C98CA573F196DCBFE1B8CC18C10AE1AFEB0E4E899C6CA4DEFC59138E170954016DCB9C007FDC7C2B2950436E24AA5FF9C0888822626C9AE01C07A98F317A9499F0E9D5E61434F959E9;ASP.NET_SessionId=o112vzki5owvbptr4kudbdax
Host:localhost:64729
Range:bytes=7339303-
Referer:http://localhost:64729/Video/Index/3
User-Agent:Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Response headers
Cache-Control:private, s-maxage=0
Connection:Close
Content-Length:23617
Content-Range:bytes 7339303-7362919/7362920
Content-Type:video/mp4
Date:Tue, 15 Jan 2013 12:55:24 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
Request
URL: http://localhost:64729/Video/GetVideo/24
Method: GET
Status Code: 206 Partial Content
Request headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:identity;q=1, *;q=0
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:.ASPXAUTH=BD5B9748E6985F5659B56289A5543C11CACBF1602AFFD5D4335453560988B870F2543269809401D13EE9F12EFBAC2D4CE0322B5F826871B9968B3D2986C01E35C536B28B5EC24E8E4F631D094B0DBEFF76DA84DA7CCC753E06C38C0FA36A858AC87548099BD23D4BE9B80434970A542489EC5E5F4543A9C98CA573F196DCBFE1B8CC18C10AE1AFEB0E4E899C6CA4DEFC59138E170954016DCB9C007FDC7C2B2950436E24AA5FF9C0888822626C9AE01C07A98F317A9499F0E9D5E61434F959E9;ASP.NET_SessionId=o112vzki5owvbptr4kudbdax
Host:localhost:64729
Range:bytes=48-
Referer:http://localhost:64729/Video/Index/3
User-Agent:Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17
Response headers
Cache-Control:private, s-maxage=0
Connection:Close
Content-Length:7362872
Content-Range:bytes 48-7362919/7362920
Content-Type:video/mp4
Date:Tue, 15 Jan 2013 12:55:24 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0

After some intensive testing (thank you for sample project) it looks like Chrome is having some issues with mp4 format.
In order to fix this situation it should be enough to move webm as the first format so Chrome will pick it up instead of mp4 (IE will skip to mp4 so it will work too):
<div id="video">
<div id="video-viewport">
<div class="flowplayer" data-swf="http://releases.flowplayer.org/5.1.1/flowplayer.swf" data-ratio="0.417" data-engine="html5" data-keyboard="true" data-native_ipad_fullscreen="true" data-volume="0.6">
<video>
<source type="video/webm" src="#Url.Action("GetVideo", "Video", new { id = Model.WebMVideo.Id })"/>
<source type="video/ogv" src="#Url.Action("GetVideo", "Video", new { id = Model.OgvVideo.Id })"/>
<source type="video/mp4" src="#Url.Action("GetVideo", "Video", new { id = Model.WebMp4Video.Id })"/>
</video>
</div>
</div>
</div>

You can try this , it fixed my problem whick seems the same with yours .
<script>
flowplayer.conf={
engine:'flash'
};
</script>

Related

unsupported media type application/x-www-form-urlencoded

I'm getting this error all of a sudden:
21:28:14.345 [debug] ** (Plug.Parsers.UnsupportedMediaTypeError) unsupported media type application/x-www-fo
rm-urlencoded
(plug) lib/plug/parsers.ex:231: Plug.Parsers.ensure_accepted_mimes/4
(api) lib/api/router.ex:1: Api.Router.plug_builder_call/2
(api) lib/plug/debugger.ex:123: Api.Router.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) /Users/Ben/Development/Projects/vepo/api/deps/cowboy/src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
When making this network request:
Request URL:http://192.168.20.6:4000/products/?p_id=1&s_id=1
Request Method:PUT
Status Code:415 Unsupported Media Type
Remote Address:192.168.20.6:4000
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
cache-control:max-age=0, private, must-revalidate
content-length:45284
content-type:text/html; charset=utf-8
date:Sun, 28 Jan 2018 08:40:36 GMT
server:Cowboy
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-GB,en-US;q=0.9,en;q=0.8
Connection:keep-alive
Content-:application/json
Content-Length:75
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:192.168.20.6:4000
Origin:http://evil.com/
Referer:http://localhost:8081/debugger-ui/debuggerWorker.js
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
X-Requested-With:XMLHttpRequest
Query String Parameters
view source
view URL encoded
p_id:1
s_id:1
Form Data
view source
view URL encoded
s_id:1
p_id:1
image:null
price:2.53
description:kcucufufi icif Gigiuyub
Code to send the request:
import { ajax } from 'rxjs/observable/dom/ajax'
return ajax({
body: action.payload,
method: 'PUT',
headers: { 'Content-': 'application/json' },
url: `http://192.168.20.6:4000/products/?p_id=${
action.payload.p_id
}&s_id=${action.payload.s_id}`
}).map(response => updateEditProductInDbFulfilled(response))
.catch(error => Observable.of(updateEditProductInDbRejected(error)))
I didn't actively change anything in my backend to not accept x-www-form-urlencoded, so why would this happen when it used to work?
Is x-www-form-urlencoded bad? What is the best approach to successfully send my network request? Change my code sending the request or changing the backend somehow to accept the request?
Backend is Elixir.
This is how I added Plug.Parsers (In my router):
if Mix.env == :dev do
use Plug.Debugger
end
plug :match
plug Plug.Parsers, parsers: [:json],
pass: ["application/json"],
json_decoder: Poison
plug :dispatch

Spring Security: How configure correctly CSRF for Ajax security control filter

I am working with Spring Security
The app has enabled the following:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/css/**", "/resources/images/**", "/resources/jquery/**", "/resources/js/**").permitAll()
... more URLs to intercept
.antMatchers("/notification**").hasAuthority("ROLE_ADMIN")
.antMatchers("/ajax/notification**").hasAuthority("ROLE_ADMIN")
.anyRequest().authenticated()
.and()
.csrf()
...
Observe CSRF is applied. For a form the following is used:
<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}"
method="post">
<input type="submit"
value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
It according Form Submissions
The app works fine how is expected, it intercepts any URL prior to load/render a jsp page and ask for the login control how is expected, if the user has logged the control about authorization is applied how is expected too. Therefore all is working with CSRF how is suggested.
Until here all is Ok.
I added ajax through jQuery and because it works with an URL, therefore I need apply the CSRF control for that URL too.
That's why above appears:
.antMatchers("/ajax/notification**").hasAuthority("ROLE_ADMIN")
Now, I want get the expected HTTP error code and message when CSRF is applied to the ajax URL "/ajax/notification" and the CSRF headers were not send.
The js ajax code is:
$.getJSON(
"/projectname-01/ajax/notification",
function(data, textStatus, req) {
console.log("data: " + data);
console.log("textStatus: " + textStatus);
console.log("req: " + req)
console.log("data: " + data);
console.log(data.content + " " + data.date);
$("#single").empty();
$("#single").append(data.content + " " + data.date);
$("#multiple").append(data.content + " " + data.date)
.append("<br/>");
}
)
Note: The URL needs to be /projectname-01/ajax/notification, the projectname-01 is mandatory, if I remove that, I get the 404. It does not work even if ./ajax/notification is used (observe the dot).
Problem: The code works fine, I mean, the Ajax call happens to the server without any problem, I am expecting some error, it because the code is not using the CRSF requeriments for ajax.
It according from:
Ajax and JSON Requests
The csrfMetaTags Tag
Thus, such as either:
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>
or
<sec:csrfMetaTags />
and of course the js code working with:
_csrf_parameter, _csrf_header etc.
Then the expected HTTP error code and message is need it for testing and production purposes
Thus, what is missing? or what is the problem?
Headers: how was requested below the HTTP headers:
From Opera
General
Request URL:http://localhost:8080/security-01/ajax/notification
Request Method:GET
Status Code:200
Remote Address:[::1]:8080
Referrer Policy:no-referrer-when-downgrade
Response Headers
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 23 Sep 2017 00:14:20 GMT
Request Headers
GET /security-01/ajax/notification HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36 OPR/47.0.2631.80
Referer: http://localhost:8080/security-01/tiles/notification/
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Cookie: JSESSIONID=9F2007DA3C8C683D26B8D17D85563140; jenkins-timestamper-offset=18000000
From Firefox
Request Headers
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8080/security-01/tiles/notification/
X-Requested-With: XMLHttpRequest
Cookie: JSESSIONID=CF344E56DD03C4019DCA334CD38B73EC
Connection: keep-alive
Response Header
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Sat, 23 Sep 2017 00:17:06 GMT
Clarification
According with Spring Security Reference Documentation we apply CSRF for a JSP page (submit form) and for Ajax, both work around with a URL. For the former I have already configured and works fine. The latter is the problem.
When I use jQuery's $.getJSON call without send the special CSRF data/headers values (<sec:csrfMetaTags />, meta[name='_csrf_parameter'] , etc), I mean from: 30.6 The csrfMetaTags Tag appears the following:
// using JQuery to send an x-www-form-urlencoded request
var data = {};
data[csrfParameter] = csrfToken;
data["name"] = "John";
...
$.ajax({
url: "http://www.example.org/do/something",
type: "POST",
data: data,
...
});
// using JQuery to send a non-x-www-form-urlencoded request
var headers = {};
headers[csrfHeader] = csrfToken;
$.ajax({
url: "http://www.example.org/do/something",
type: "POST",
headers: headers,
...
});
From above it sends the CRSF information either from data or headers. But in my code I am not sending that. Therefore I expect some special control and error reported through Spring Security
Thus with my current ajax code, through development in runtime (Tomcat running with the app), the call to the server happens and data is returned. Thus Spring Security did not intercept and throw an error due the absence of these CRSF data/headers.
Therefore thinking now for development and testing, if I create #Test methods where should fail because the CSRF data/headers values were not send. The #Test methods are going to fail because the call to the server happens without any security control.
Your HTTP GET request produces no error, because the CSRF token is only required for requests that update state, see Spring Security Reference:
18.2 Synchronizer Token Pattern
[...]
We can relax the expectations to only require the token for each HTTP request that updates state. This can be safely done since the same origin policy ensures the evil site cannot read the response. Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked.
and CsrfFilter:
Applies CSRF protection using a synchronizer token pattern. Developers are required to ensure that CsrfFilter is invoked for any request that allows state to change. Typically this just means that they should ensure their web application follows proper REST semantics (i.e. do not change state with the HTTP methods GET, HEAD, TRACE, OPTIONS).
To get a CSRF token you have to use HTTP POST, PUT or DELETE request.

odata query works again ApiController but does not work again ODataController

I try use System.Web.OData.ODataController in WebAPI 2.
WebConfig.cs
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<User>("User");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: builder.GetEdmModel());
Controller:
public class UserApiODataController : ODataController
{
[Route("api/lookups/users")]
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IHttpActionResult GetUsers()
{
try
{
var context = new DbContenxt();
return Ok(context.Users.AsQueryable());
}
catch (Exception exception)
{
return InternalServerError(exception);
}
}
}
When I try query data I get error:
GET http://localhost:58786/api/lookups/users 406 (Not Acceptable)
When I replace ODataController with ApiController query works good.
Request Header:
Accept:application/atomsvc+xml;q=0.8, application/json;odata=fullmetadata;q=0.7, application/json;q=0.5, */*;q=0.1
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
DataServiceVersion:2.0
Host:localhost:58786
MaxDataServiceVersion:2.0
Origin:http://localhost:62131
Pragma:no-cache
Referer:htpp://localhost:62131/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
ODataController Response header:
Remote Address:[::1]:58786
Request URL:http://localhost:58786/api/lookups/users
Request Method:GET
Status Code:406 Not Acceptable
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:62131
Cache-Control:no-cache
Content-Length:0
Date:Mon, 30 Nov 2015 16:09:25 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpccHJvamVjdHNcZG9rdW1lbnRhXFN3YWxsb3dcU3JjXFN3YWxsb3cuV2ViQXBpXGFwaVxsb29rdXBzXExpY2Vuc2VUeXBl?=
ApiController Response Header
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:62131
Cache-Control:no-cache
Content-Length:247
Content-Type:application/json; charset=utf-8
Date:Mon, 30 Nov 2015 16:20:53 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpccHJvamVjdHNcZG9rdW1lbnRhXFN3YWxsb3dcU3JjXFN3YWxsb3cuV2ViQXBpXGFwaVxsb29rdXBzXExpY2Vuc2VUeXBl?=
On client side I use JayData.
What is wrong ? Any idea?
First, from the namespace System.Web.OData.ODataController, I think you are using the Web API OData V4 library. V4 doesn't accept application/atomsvc+xml because only "Json" is the standard in OData V4 spec.
Second, odata=fullmetadata is the OData V3 metadata header, for V4, it should be odata.metadata=full
Third, [Route("api/lookups/users")] is Web API attribute. If you want to use ODataController, please use the OData version. [ODataRoute("...")]
Fourth, please make sure the route template in [Route(...)] follows up the OData Uri conventions. See more detail here
Fifth, you can get more tutorial from here.
Hope it can help you. Thanks.

AngularsJS POST JSON data to Symfony2

I would like to know why this is not working , I have a AngularJS app witch sends trough AJAX data to a Symfony2 Application. As you can see, data is sent in my network console
<?php
namespace Supbox\CloudBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
class FolderController extends Controller
{
public function createAction(){
$post = $this->getRequest()->request;
$name = $post->get("name");
$folder = $post->get("folder");
var_dump($post);
die;
}
}
AngularJS code
$http({
method: 'POST',
url: route.folder.create,
data: {
folder: $scope.id,
name: name
}
})
Opera Network Console Output
Request URL:http://localhost/supbox/web/box/folder/create
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept-Encoding:gzip,deflate,lzma,sdch
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:25
Content-Type:application/json;charset=UTF-8
Host:localhost
Origin:http://localhost
Referer:http://localhost/supbox/web/box/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 OPR/20.0.1387.82
Request Payloadview source
{folder:1, name:Ang}
Response Headersview source
Connection:Keep-Alive
Content-Length:431
Content-Type:text/html
Date:Mon, 24 Mar 2014 13:25:53 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.4 (Win64) OpenSSL/1.0.1d PHP/5.4.12
X-Powered-By:PHP/5.4.12
If you (Angular JS) post data through header as JSON you need to change your code like this:
public function createAction(){
$post = $this->getRequest()->getContent();
$post = json_decode($post);
$name = $post->name;
$folder = $post->folder;
var_dump($post);
var_dump($name); // null
var_dump($folder); // null
die;
}
Dont know why, Angular $http sends data as request body, JSON encoded whereas Symfony2 is reading $_GET and $_POST arrays.
So you got 2 solutions:
1- Update Php code, you could override SF2 Request class (https://gist.github.com/ebuildy/fe1e708e466dc13dd736)
2- Update Js code, you can "transform" the $http request (https://gist.github.com/bennadel/11212050)
A bundle has been created to solve this problem, and it's very light.
qandidate-labs/symfony-json-request-transformer

AngularJs - JSON post

I tried to post username and password to api, but looks like it doesnt work as simple as jquery post. I keep geting this 400 error.
Code:
$http({
method: 'POST',
url: apiLink + '/general/dologin.json',
data: {"username":"someuser","password": "somepass"}
}).success(function(response) {
console.log(response)
}).error(function(response){
console.log(response)
});
But if I add this line:
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
and change data to:
data: "username=someuser&password=somepass"
it works. But the thing is, that I have to use json.
And detailed informations from Google Chrome:
Request URL:http://coldbox.abak.si:8080/general/dologin.json
Request Method:POST
Status Code:400 Bad Request
Request Headersview source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en,sl;q=0.8,en-GB;q=0.6
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:57
Content-Type:application/x-www-form-urlencoded
Host:coldbox.abak.si:8080
Origin:http://localhost:8888
Referer:http://localhost:8888/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36
Form Dataview sourceview URL encoded
{"username":"someuser","password":"somepass"}:
Response Headersview source
Access-Control-Allow-Origin:*
Connection:close
Content-Length:49
Content-Type:application/json;charset=utf-8
Date:Wed, 02 Apr 2014 07:50:00 GMT
Server:Apache-Coyote/1.1
Set-Cookie:cfid=b5bbcbe2-e2df-4eef-923f-d7d13e5aea42;Path=/;Expires=Thu, 31-Mar-2044 15:41:30 GMT;HTTPOnly
Set-Cookie:cftoken=0;Path=/;Expires=Thu, 31-Mar-2044 15:41:30 GMT;HTTPOnly
I'm betting it's a CORS issue if your angular app isn't on the exact same domain as the server to which you're posting your JSON.
See this answer for details: AngularJS performs an OPTIONS HTTP request for a cross-origin resource
Try
data: {username:"someuser",password: "somepass"}
without the quotes around the username and password and see if that makes a difference.
You would have to transform the data with a JSON.stringify when you assign that to the data

Resources