Home > Software design >  Calling an API client side from webpage served by Express
Calling an API client side from webpage served by Express

Time:01-30

I'll keep it short, I am getting a CSP (Content Security Policy) error when using the Fetch API in my client-side code. I cannot change the CSP because the request CSP is more strict than connect-src 'self' http://localhost:5000 (the meta tags of the page and 'use' functions in the middleware had no effect on the request CSP).

Maybe I'm missing something, there must be a way for client-side code to call an API?

Error: enter image description here

Relevant code:

let USER_DETAILS = null;

async function get_by_api(url, data) {
    const res = await fetch(url, {
        method: "POST",
        headers: {'Content-Type': 'application/json; charset=UTF-8'},
        body: JSON.stringify(data)
    });
    // res.catch(function (_) {
    //     alert("Internal error. Please try again later.\nWe are sorry for the inconvenience.");
    //     localStorage.clear();
    //     window.location.replace("https://example.com");
    // });
    return res;
}

async function update_user_display() {
    let user_email = localStorage.email;
    let user_key = localStorage.app_key;
    console.log("User email: "   user_email);
    console.log("User key: "   user_key);
    let user_res_data = await get_by_api("http://localhost:5000/v1/info", {
        "email": user_email,
        "key": user_key
    });
    user_res_data.then(async function (res) {
        if (!(res.status === 200)) {
            alert("Internal error. Please try again later.\nWe are sorry for the inconvenience.");
            localStorage.clear();
            window.location.replace("https://example.com");
            return;
        }
        USER_DETAILS = await res.json();
        document.getElementById("tb_user").innerHTML = USER_DETAILS.name;
    });
}

fyi: localhost:5000 is what the test API is running on and localhost:5555 is what the app is running on

Thanks for any help.

CodePudding user response:

Check the response headers when your page (response with content type "text/html") loads. You will likely see a CSP header with "default-src 'self'" there. This is the policy you need to change. First you will need to identify where it is set and then how your can change or override it.

CodePudding user response:

Maybe I'm missing something, there must be a way for client-side code to call an API?

By default you just need the API server to grant permission to access it's data across origins via CORS.

In this case http://localhost:5000 has a CSP which prevents code in its pages from accessing anything other than http://localhost:5000. That's an explicit extra level of security that http://localhost:5000 has turned on (one key benefit is that it helps against XSS attacks). If you want to access http://localhost:5555 then you need to change the CSP to say that http://localhost:5555 is trusted (i.e. that you know it isn't a malicious site being used for XSS).

You say you can't change the CSP (it isn't clear why; http://localhost:5000 is your local development environment!) so you can't do that. This means that in your case it isn't possible to call that API.

  • Related