this post was submitted on 04 Jul 2023
5 points (100.0% liked)

Web Development

3431 readers
1 users here now

Welcome to the web development community! This is a place to post, discuss, get help about, etc. anything related to web development

What is web development?

Web development is the process of creating websites or web applications

Rules/Guidelines

Related Communities

Wormhole

Some webdev blogsNot sure what to post in here? Want some web development related things to read?

Heres a couple blogs that have web development related content

CreditsIcon base by Delapouite under CC BY 3.0 with modifications to add a gradient

founded 1 year ago
MODERATORS
 

Hello, I have a problem with CORS and I think this is right community to get help.

When I use this code:

import { LemmyHttp } from 'lemmy-js-client';
const client = new LemmyHttp('https://lemmy.ml');
const { posts } = await client.getPosts({
    limit: 10,
    page: 1
});

to get posts from lemmy.ml (using lemmy-js-client), I get:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://lemmy.ml/api/v3/post/list?limit=10&page=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 400.

I have tried to add header like this:

const client = new LemmyHttp('https://lemmy.ml', {
    headers: {
        'Access-Control-Allow-Origin': '*'
    }
});

but result is the same.

Can someone help me with this?

you are viewing a single comment's thread
view the rest of the comments
[–] data0 3 points 1 year ago* (last edited 1 year ago) (1 children)

The Access-Control-Allow-Origin is meant to be set on the server side and is part of a mechanism called CORS. MDN has a good guide on CORS (It might seem too long and complex to read if you just want to access some data on an API, but knowing how it works is essential if you plan to work with HTTP-based APIs.)

In short, lemmy.ml (and probably most other Lemmy instances) doesn't seem to allow API access from within a browser. You'll have to build a Node.js proxy (with lemmy-js-client) and use that to connect the browser to.

[–] starman 2 points 1 year ago* (last edited 1 year ago)

Thanks for the link, I'll read it.