Showing posts with label fetch. Show all posts
Showing posts with label fetch. Show all posts

Tuesday 18 April 2023

JavaScript fetch, VS Code, CORS, Debugging and curl

I've recently been trying to use the Pocket API to bring my favourite links into a page. Naturally, I was starting from a position of testing it on localhost. I've also been using VS Codium, which has improved on Ubuntu. I use the Brave browser and so was looking to make use of this in my debugging.

So first things, first I needed to get debugging happening in VS Codium using Brave on Ubuntu. As you try and run the debugger, you have the option to create a launch.json file for your project. Here, I selected to create a Chrome web app. Once the launch.json was created, I edited it with the following, in order that the debugger used Brave:

{

    "version": "0.2.0",

    "configurations": [

        {

            "type": "chrome",

            "request": "launch",

            "name": "Brave",

            "runtimeExecutable": "/opt/brave.com/brave/brave-browser",

            "userDataDir": true,

            "url": "http://localhost:5500",

            "webRoot": "${workspaceFolder}",

            "runtimeArgs": ["--disable-web-security"]

        }

    ]

}

I the setting "--disable-web-security" fixed the CORS problem commonly faced such as,

Access to fetch at ‘http://localhost:8000/api/v1/messages’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

The final issue I encountered was the code itself. I'd successfully retrieved the data I was looking for using curl, but converting the curl command to a JavaScript fetch was problematic. I then came across this page which helped.

Now we're cooking!


Thursday 7 March 2019

Using the Vanilla JS Component template with LAMP

I use the Vanilla JS Component at https://github.com/guitarbeerchocolate/vanilla-js-component, and you have LAMP server on my box. However, when I want to call PHP scripts which are on the LAMP server such as, in a POST request using fetch or XHR within JavaScript I get the following errors in my browser:
Access to XMLHttpRequest at 'http://localhost/test/vanilla-js-POST-JSON/login.php' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

postjson_xhr.js:19 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost/test/vanilla-js-POST-JSON/login.php with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Obviously, it's treating the LAMP server like another domain.

The way to fix this is to put a line at the top of your PHP script thus:
header('Access-Control-Allow-Origin: *');
Happy coding.

Wednesday 6 February 2019

Vanilla JavaScript Login form POST handler using fetch

I've been updating my gists lately because I'm now in position to leave jQuery behind. See https://gist.github.com/guitarbeerchocolate
So, here's how to pass login form data to some middleware and accept JSON in return using fetch.

const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  fetch(url, {
    method: method,
    body: new FormData(form)
  }).then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('json.username', json.username)
    console.log('json.password', json.password)
  }).catch(function(error) {
    console.log('parsing failed', error)
  })
});

Monday 14 May 2018

Get blogspot content using JavaScript fetch

This example pulls in JSON data from a blog hosted on blogspot.com

First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

const fetch = require('node-fetch');
const url = 'http://some-website.blogspot.com/feeds/posts/default/-/blog?alt=json';
var myFetch = fetch(url);

myFetch.then(response => response.json()).then(function(data) {
  showMyData(data);
}).catch(function(err)
{
  console.log('Caught an error ',err);
});

function showMyData(md) {
  md.feed.entry.forEach((e) => {
    var title = (e.title.$t || '');
var url = (e.link || []).pop().href;
    var date = new Date(e.updated.$t || Date.now());
    var lessLines = e.content.$t.substr(0, 800);
    var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var theMonth = months[date.getMonth()];
    var theYear = date.getFullYear();
  });
}

Friday 11 May 2018

The 2018 Web Developer : JavaScript JSON processing without jQuery

Enter 'fetch'. The JavaScript API which performs HTTP requests.
First, I'll need to get fetch.
To add it to your project, change to your project directory:
cd myApp
Then use the following command:
npm install node-fetch --save

In this example, I have a simple .json file which contains a set of URLs and their types.

const fetch = require('node-fetch');
const url = 'feeds.json';
var myFetch = fetch(url);

myFetch.then(response=>response.json()).then(function(data) {
    showMyData(data);
  });

function showMyData(md)
{
  md.forEach((value) => {
    console.log(value.URL, value.TYPE);
  });
}