Home > OS >  Trying to GET from 4chan API
Trying to GET from 4chan API

Time:05-28

I'm trying to make a GET request to this endpoint https://a.4cdn.org/boards.json of the 4chan API https://github.com/4chan/4chan-API.

The documentation says:

CORS is supported from origins boards.4chan.org or boards.4channel.org, via http:// or https://. 

When I access this endpoint in my browser I get the JSON just fine but when I make a request in my Angular app I get a response back with:

headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for https://a.4cdn.org/boards.json: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "https://a.4cdn.org/boards.json"

Here's my code:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class BoardsService {

  constructor(private http: HttpClient) { }

  getBoards() {
    this.http.get('https://a.4cdn.org/boards.json').subscribe({
      next: (data) => {
        console.log(data);
      },
      error: (err) => {
        console.log(err);
      },
      complete: () => {
        console.log('complete');
      }
    });
  }
}

Is anyone able to get this working?

I hope I don't need to create an API just use another API

CodePudding user response:

The easiest solution to all third party API CORS errors is to make the call through your backend.

CodePudding user response:

You have run into a CORS issue.

Essentially, this 4chan API cannot be used from the browser, unless done from a page hosted on 4chan. The workaround is to fetch from a server, as it's not a web browser, and does not enforce CORS rules.

You don't have to host the server yourself, there are plenty of existing services designed to circumvent CORS (see cors-anywhere for example). Note that this is not a good idea for production code, for example, someone could hijack the CORS redirection server and do bad stuff.

You are recommended to make your own API, or alternatively, host some simple server to get around CORS (like cors-anywhere).

  • Related