2

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

nandesuka
  • 699
  • 8
  • 22
  • 1
    The CORS error says it all. If your origin (web browser base url in this case) isn't `boards.4chan.org` or `boards.4channel.org`, CORS will block the request. You'll need to fetch this resource a different way (eg, fetch on the backend using node or something) – CollinD May 26 '22 at 06:39
  • May be this topic can help you: https://stackoverflow.com/questions/43749426/trying-to-get-cors-to-work-for-4chan-api – Valentine Nazarov May 26 '22 at 06:59

2 Answers2

1

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).

AlexApps99
  • 3,506
  • 9
  • 21
1

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

Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35