Js Fetch Local File

Posted on  by admin
Modified4 months ago.

I would like to use the fetch method on a relative path such as :.

The reason is as follows : I am testing my code on multiple different computers, sometimes with a different port.

I would like this code to work in a dev and in a prod environment in order to have to remember to change the used urls on a per-computer / server basis ( witch introduces a lot of unwanted potential issues ).

How can I get the data from my local api route ?

I could not figure out why does the fetch method not do local routes nor a workaround. The solution turned out to be a lib called superjson.

I was attempting to put my code into the API because I could not use getServerSideProps properly with prisma ( it returns Date objects that cannot be serialized in JSON ).
Thus I was trying to use the API paths as the response there is properly serialized but ran into the issues that made me write this question.
1

The complete solution is to write the method in a common file ( this allows for the factorisation ), use the lib superjson to properly serialize the object and call that method in the getServerSideProps method.

This allows for clean code that is nextjs compatible.

Matthieu Raynaud de Fitte.
1

11 gold badge1616 silver badges3333 bronze badges. 3333 bronze badges.

  1. You can do it like this fetch('http://localhost:3000/api/get_all_prices')or replace the base URL with a variable fetch(baseUrl + 'api/get_all_prices') which might cause error: Only absolute paths are supported.However, you should only call local API for testing because..

  2. You should not use fetch() to call an API route in getServerSideProps.

this is mentioned in the documentation. It is recommended to write your logic directly inside getServerSideProps.This applies to getStaticProps too.

jsejcksnjsejcksn
12.8k1

Not the answer you're looking for? Browse other questions tagged reactjsjsonfetchlocal or ask your own question.