2

I am trying to send a request to Exist API using next.js the backend in PHP I am trying to send a post request (Axios)with data and see the response who can I handle this API in my code I read that I need to put some code in the API file but I didn't get how? where I should but my endpoint?

export default Login;
  • next.js does not require any additional API settings it works very similar to Reactjs except with the difference being in CSR (Client Side Rendering) and SSR(Server Side Rendering). Could you please elaborate on the error that you are getting. – Ujwal Agrawal Aug 22 '20 at 17:13
  • error in request Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:91) – Afnan Shawawreh Aug 22 '20 at 17:51

1 Answers1

1

your next.js code is fine and the error that you have mentioned in the comment occurs when the Axios library is not able to communicate with the server due to Internet Connection issue, CORS policy etc.

I have tried running your code on my system and this is what I get in my console

enter image description here

enter image description here

I have tried running the API call using postman and it seemed to work properly. So reason 1 is ruled out and the only reason for your error is CORS as shown in the image.

I have also replaced your API call with mine and the code seems to work flawlessly. So be assured it's not an issue with nextjs or Axios.

Also Note that if you are willing to send cookies to the server that has a domain different than the one your nextjs is running on then you will be needed to add withCredentials: true in axios. Something like this.

axios.get('url', {withCredentials: true});

Solution:

Allow your port (for example localhost:3000) on your server's allowed origin to access it.

header('Access-Control-Allow-Origin: *'); 

To enable CORS in PHP have a look at this solution: Cross-Origin Request Headers(CORS) with PHP headers

Hopefully, this solves your problem. If it still doesn't then please do comment below.

Ujwal Agrawal
  • 454
  • 7
  • 8
  • I handle the CORS In the php and i can see it in the response header in postman but I still face the same error – Afnan Shawawreh Aug 23 '20 at 14:34
  • @AfnanShawawreh CORS issue could not be identified very well in Postman as it is a development tool and it does not enforces CORS policy. Here is the link that explains the same. https://stackoverflow.com/questions/36250615/cors-with-postman. Try this in Chrome Browser. Go to Inspect -> Console -> Log Level -> Select Error and Info. Now try submitting your request and see if you see the CORS error in the console. If yes then your backend still does not allow cross-origin API calls. If you do not see the error then do let me know. – Ujwal Agrawal Aug 23 '20 at 16:05