Enabling CORS in CakePHP app - php

I am trying to enable CORS for an API built in CakePHP so that all requests are accessible with the following in the AppController:
public function beforeFilter()
{
header("Access-Control-Allow-Origin: *");
}
Is this in the wrong place? As requests are still being blocked.
Update: It seems this does in fact work BUT because I am doing something like:
header('Content-Type: application/json');
echo json_encode(array('message'=>'Hello world!'));
In some of my methods it's acting as though it's overriding the header set the AppController so it's not appearing in the response for the JSON calls.
Any ideas?
Update 2: Returning JSON like below, fixes the problem:
$this->response->type('json');
$this->response->body(json_encode(array('message'=>'Hello world!')));
So apparently using header() in Cake breaks previous headers?

You can do this using the cake response object;
$this->response->header('Access-Control-Allow-Origin', '*');
More info on the response object;
http://book.cakephp.org/2.0/en/controllers/request-response.html#setting-headers
However, the beforeRender() callback seems a more logical location.
Another option is to add this header in your apache vhost or htaccess examples can be found in the htaccess file of Html5Boilerplate which is a very interesting thing to look at (well documented), because it contains a lot of optimisations that work nicely with cakephp as well;
https://github.com/h5bp/server-configs-apache/blob/master/dist/.htaccess
http://html5boilerplate.com/

Based on what I found out here: Sending correct JSON content type for CakePHP
The correct way to return JSON in CakePHP is like so:
$this->response->type('json');
$this->response->body(json_encode(array('message'=>'Hello world!')));
This is because the headers can be overridden and therefore the CORS doesn't work unless you do it the 'proper' way using the response object in Cake.

Related

Symfony 2.7 set header from StreamedResponse's callback

I have to set dynamically my Content-Type into the StreamedResponse's callback.
I wrote a code like this that it works fine on Symfony 2.3 but not on 2.7. The returned Content-Type is text/html.
function indexAction()
{
$r = new \Symfony\Component\HttpFoundation\StreamedResponse();
$r->setCallback(function() use ( & $r)
{
// ...
$r->headers->set('Content-Type', 'application/json');
// ...
});
return $r;
}
I found this commit that it can be on but i don't really understand...
https://github.com/symfony/http-foundation/commit/6a0838a26d54eff153b825e1550c1f6fa05a0941
It looks like we can now only set header outside the callback.
It works if i send headers with the native php function into the closure but it's dirty...
header('Content-Type: application/json');
if someone has a clue...
Thanks!
Streamed response made for purposes when you need long-polling connections. And so you have to know what content-type it will serve before you send any data.
When you return your Response object in action Symfony already sends headers and starts to stream output from callback function. In this moment it is not right to send another header.
P.S. I have never seen case when you really need StreamedResponse and need to set Content-Type dynamically.
To be accurate, you can use hack with replacing headers up to version 2.7.19, it was merged in 2.7.20
As #MichaelSivolobov said in his answer, I also have never seen cases when you need it
I'm sure such commits are always made for enforce better application design. When I see such cases as in your example, it's a some kind of red flag to rethink code/data flow

Set Request (not Response) Headers in Laravel 5 for Non-Ajax Routes

I am actually completely baffled that this is such a difficult task to accomplish and/or find any relevant information about. My guess is that it must be something SO simple, that no one has to ask about it (except for me! :-) ), so I am hoping that someone can easily point me in the right direction...
I need to set headers in my Requests - not in my Responses (I've got that part handled), and not for Ajax routes (I've got that part handled as well). How on Earth do I accomplish this on internal app routes in Laravel 5.1?
Essentially, I need to attach an 'Authorization' header to certain Requests. (i.e.
$request->headers->set('Authorization', 'my-authorization-token');
)This line of code does not work, however. No matter where I put it. It doesn't work from middleware. It doesn't work from routes.php. It doesn't work from my controllers... it just simply does not work period. (For the sake of clarity, '$request' is 'Illuminate\Http\Request').
What am I missing? Where/How can I set request headers before a request is sent? Please help! Thanks in advance.
Some of the answers here might give you an idea, you could adapt them for the request: Where can I set headers in laravel
This also looks relevant: Laravel 5 / Lumen Request Header?
The request is sent from the client to the server (i.e. your Laravel app). So you set the request headers on the client site using Javascript.
The Laravel documentation has an example of setting the X-CSRF-TOKEN header using jQuery.
$.ajaxSetup({
headers: {
'X-MY-HEADER': 'whateveryouwant
}
});
Using VueJS it would look like this
Vue.http.headers.common['X-MY-HEADER'] = 'whateveryouwant';
You need to create a new request object and then set the header like this:
// e.g., Inside controller method
$request = new \Illuminate\Http\Request();
$request->setMethod('POST'); // or whatever your request type is
$request->header('Authorization', 'my-authorization-token');

Content type in codeigniter

I have a controller in CodeIgniter which have few functions in it. For ajax interaction, in some functions where i had to return json objects, i did the following :
$this->output->set_content_type("application/json");
The ajax is working fine. But now when i'm trying to echo something from a function and going to that function in browser gives me the following :
Content Encoding Error
The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression.
I tried setting content type to "text/html", i don't know. Also i tried removing all those content type set. That also didn't help me echoing out of the controller.
What should i do, to echo something out of a specific controller function just in case for testing purposes?
You seem to have GZIP compression turned on in your config. it might mess with your AJAX transfers and/or caching.
By default you don't need to give a content-type when serving json encoded data. So it's better to leave the whole content-type out to prevent future issues. Besides that it's also handy because there can be occasions where you might have one AJAX call give either a JSON encoded string or just a piece of output.
Good luck!

CodeIgniter RESTful API Library Response

This question is related to the CodeIGniter RESTful API library found here. I hope someone here is using this library and can offer some help :) .
http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
I have installed this library and set up a working environment with it. I have been able to get data back as well. For use, I have created a very simple class that I am accessing with the following code:
<?php
require APPPATH.'/libraries/REST_Controller.php';
class Users extends REST_Controller
{
public function list_get()
{
$this->load->database();
$data = $this->db->get('users')->result();
$this->response($data, 200);
}
}
To get at this controller, I have done a call to the following URL:
"http://localhost/mgtapp/index.php/api/users/list/format/json"
While I am getting back data, I see that the header content type is set to text/html instead of json and I am also getting errors in php that say "headers already sent". I have tried to remove the format from the end of the url and send it in via an "accept" but I get the same errors and I see the content type being set as text/html. When I run the example, I see the response coming back as it should (as json in the content type) so I do not understand what I am doing wrong here that the content type is not being set correctly. IF someone can shed some light it would be super helpful!
Thanks!
So I am answering this question because the reason for my troubles was a stupid one.
I had a couple of lines under the "?>" of my php class controller and apparently that was messing it up. Sorry!
Anybody else with this issue, check that first!

How can I implement jquery in my Zend Framework application in a custom manner?

How can I implement jquery in my Zend Framework application in a custom manner.
appending jquery.js ok
appending script ok
send POST data to controller ok
process POSTed data ok
send 'AjaxContext' respond to client now ok (thanks)
I'm using jquery for the first time, what am I doing wrong?
Early on, the best practice to get Zend to respond to ajax requests without the full layout was to check a variable made available via request headers. According to the documentation many client side libraries including jQuery, Prototype, Yahoo UI, MockiKit all send the the right header for this to work.
if($this->_request->isXmlHttpRequest())
{
//The request was made with via ajax
}
However, modern practice, and what you're likely looking for, is now to use one of two new helpers:
ContextSwitcher
AjaxContent
Which make the process considerably more elegant.
class CommentController extends Zend_Controller_Action
{
public function init()
{
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('view', 'html')
->initContext();
}
public function viewAction()
{
// Pull a single comment to view.
// When AjaxContext detected, uses the comment/view.ajax.phtml
// view script.
}
Please Note: This modern approach requires that you request a format in order for the context to be triggered. It's not made very obvious in the documentation and is somewhat confusing when you end up just getting strange results in the browser.
/url/path?format=html
Hopefully there's a workaround we can discover. Check out the full documentation for more details.
Make sure your using $(document).ready() for any jQuery events that touch the DOM. Also, check the javascript/parser error console. In Firefox it's located in Tools->Error Console. And if you don't already have it installed, I would highly recommend Firebug.
This should have been a comment, can't, yet...
It has nothing to do with ZF+Jquery combination.
First try a proto of what you need with a simple php file. No framework, just Jquery and straight forward, dirty php.
Oh, and don't forget to track what happens with FireBug.

Categories