Home > Enterprise >  fetch function not working in a js static file
fetch function not working in a js static file

Time:12-27

Here is my express project architecture

public
-- js
---- script.js
views
-- index.ejs
app.js

When I put my js script that contain the function fetch() directly in the .ejs file, all works perfectly.

But when I try to put my js script in the script.js static file, I get the following error :

Access to fetch at 'http://api.themoviedb.org/3/person/<%= game.id_beg.id_tmdb; %>/movie_credits?api_key=16f8c447ca077fe65e29f403f18652b0&language=en-US' from origin 'http://localhost:3000' 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.

I call the js static file in the ejs file the following way

<script src="/js/script.js"></script>

And I had the following lines in app.js

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs'); 

app.use(express.static(path.join(__dirname, 'public')));

Here is the code that contain fetch function:

function fetchMovieCast(id, title) {

    id_stack.push([id, title]);

    let req = movie_req   id   "/credits?api_key="   api_key   "&language=en-US";
    fetch(req)
    .then(res => res.json())
    .then(data => {

        showCast(data.cast, title);
    })
    .catch(err => console.log(err));
}

How do I correct my fetch error ?

Thank you for your answers

CodePudding user response:

When I attempt to decode the URL you are using, I get this:

http://api.themoviedb.org/3/person/<%= game.id_beg.id_tmdb; %>/movie_credits?api_key=xxxxxxx&language=en-US

That does not look like a legit URL. I think you have a problem in the URL you're building. It appears you have something from the EJS template that is stuck in a variable you're trying to use in constructing the URL (judging by the <%= in the URL).

And, when you move this out of the EJS file, this variable isn't getting processed by EJS so the template stuff is left in the variable which you then put into the URL and thus its a bad URL. You will either need to leave this variable in the EJS file so it can get built properly by EJS or you will need to rethink how you generate this variable in your separate Javascript file.

I'm not sure why that results in a CORS error, but you will need to fix the URL generation first and then see if there's any remaining problem.

  • Related