CodeIgniter Forums
JavaScript Fetch returns an error when in development mode. - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Model-View-Controller (https://forum.codeigniter.com/forumdisplay.php?fid=10)
+--- Thread: JavaScript Fetch returns an error when in development mode. (/showthread.php?tid=91276)



JavaScript Fetch returns an error when in development mode. - Renta Ardhana - 07-12-2024

I want to test my API call using CI4. In development mode, I encountered errors in the browser console. How can I fix this?

.env
PHP Code:
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------

CI_ENVIRONMENT development 

Controller: TesApi.php
PHP Code:
public function tesApi()
    {
        $data = ['id' => 1];
        return json_encode($data);
    

View: tesapi.php
PHP Code:
<body>
    Api test using fetch when in development mode
    
<script>
    fetch('tesapi')
        .then(response => response.json())
        .then(json => console.log(json));
    </script>
</
body

Error in browser console:
Code:
Uncaught (in promise) SyntaxError: Unexpected token '<', "<script cl"... is not valid JSON

Code:
<script class="kint-rich-script">void 0===window.kintShared&&(window.kintShared=function(){"use strict";var e={dedupe:function(e,n){return[].forEach.call(document.querySelectorAll(e),function(e){e!==(n=n&&n.ownerDocument.contains(n)?n:e)&&e.parentNode.removeChild(e)}),n},runOnce:function(e){"complete"===document.readyState?e():window.addEventListener("load",e)}};return window.addEventListener("click",function(e){var n;e.target.classList.contains("kint-ide-link")&&((n=new XMLHttpRequest).open("GET",e.target.href),n.send(null),e.preventDefault())}),e}());
void 0===window.kintRich&&(window.kintRich=function(){"use strict";var l....



RE: JavaScript Fetch returns an error when in development mode. - ozornick - 07-12-2024

Disable toolbar for API URLs   Big Grin
https://codeigniter4.github.io/userguide/incoming/filters.html#except-for-a-few-uris


RE: JavaScript Fetch returns an error when in development mode. - Renta Ardhana - 07-12-2024

(07-12-2024, 10:53 AM)ozornick Wrote: Disable toolbar for API URLs   Big Grin
https://codeigniter4.github.io/userguide/incoming/filters.html#except-for-a-few-uris
yes it works. I moved toolbar filter from required to globals. Then add exception on it.

Code:
public array $required = [
        'before' => [
            'forcehttps', // Force Global Secure Requests
            'pagecache',  // Web Page Caching
        ],
        'after' => [
            'pagecache',  // Web Page Caching
            'performance', // Performance Metrics
            // 'toolbar',    // Debug Toolbar <-- I comment out
        ],
    ];

then..
Code:
public array $globals = [
        'before' => [
            // 'honeypot',
            'csrf' => ['except' => 'api/*'],
            // 'invalidchars',
        ],
        'after' => [
            // 'honeypot',
            // 'secureheaders',
            'toolbar' => ['except' => 'api/*'], // <-- copy to here and add exception
        ],
    ];



RE: JavaScript Fetch returns an error when in development mode. - kenjis - 07-15-2024

(07-12-2024, 10:53 AM)ozornick Wrote: Disable toolbar for API URLs   Big Grin
https://codeigniter4.github.io/userguide/incoming/filters.html#except-for-a-few-uris

This works, but not good. Because if you send correct responses, you don't need to disable the toolbar filter.


RE: JavaScript Fetch returns an error when in development mode. - kenjis - 07-15-2024

PHP Code:
    public function index()
    {
        $data = ['id' => 1];
        return json_encode($data);
    

Code:
$ curl localhost:8080 -v
...
* Request completely sent off
< HTTP/1.1 200 OK
< Host: localhost:8080
< Date: Mon, 15 Jul 2024 22:29:11 GMT
< Connection: close
< X-Powered-By: PHP/8.1.29
< Cache-Control: no-store, max-age=0, no-cache
< Content-Type: text/html; charset=UTF-8
<
{"id":1}
<script  id="debugbar_loader" data-time="1721082551.730907" src="http://localhost:8080/index.php?debugbar"></script><script  id="debugbar_dynamic_script"></script>...

PHP Code:
    public function index()
    {
        $this->response->setHeader('content-type''application/json');
        $data = ['id' => 1];
        return json_encode($data);
    


Code:
$ curl localhost:8080 -v
...
* Request completely sent off
< HTTP/1.1 200 OK
< Host: localhost:8080
< Date: Mon, 15 Jul 2024 22:31:11 GMT
< Connection: close
< X-Powered-By: PHP/8.1.29
< Cache-Control: no-store, max-age=0, no-cache
< Content-Type: application/json
< Debugbar-Time: 1721082671.745205
< Debugbar-Link: http://localhost:8080/index.php?debugbar_time=1721082671.745205
<
* Closing connection
{"id":1}



The following code is better.

PHP Code:
    public function index()
    {
        $data = ['id' => 1];
        return $this->response->setJSON($data);
    

https://codeigniter.com/user_guide/outgoing/response.html#setting-the-output


RE: JavaScript Fetch returns an error when in development mode. - Renta Ardhana - 07-16-2024

(07-15-2024, 03:36 PM)kenjis Wrote: The following code is better.

PHP Code:
    public function index()
    {
        $data = ['id' => 1];
        return $this->response->setJSON($data);
    

https://codeigniter.com/user_guide/outgoing/response.html#setting-the-output

thanks @kenjis, I need to get used to this (the better)
PHP Code:
$this->response->setJSON ($var)  

or this one:
PHP Code:
public function index()
    {
        $this->response->setHeader('content-type''application/json');
        $data = ['id' => 1];
        return json_encode($data);