Reputation: 3262
I have a working API in Laravel. Tested using Postman.
The Laravel project folder and the Next.js project folder are inside the same parent laravel-next
folder. (Laravel is served at localhost:8000
and Nextjs is served at localhost:3000
)
To get list of all items I use this API endpoint: http://localhost:8000/api/products/
.
This is the php artisan route:list
output:
+--------+-----------+------------------------+------------------+------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+-----------+------------------------+------------------+------------------------------------------------+------------|
| | GET|HEAD | api/products | products.index | App\Http\Controllers\ProductController@index | api |
| | POST | api/products | products.store | App\Http\Controllers\ProductController@store | api |
| | GET|HEAD | api/products/{product} | products.show | App\Http\Controllers\ProductController@show | api |
| | PUT|PATCH | api/products/{product} | products.update | App\Http\Controllers\ProductController@update | api |
| | DELETE | api/products/{product} | products.destroy | App\Http\Controllers\ProductController@destroy | api |
I already inserted a few rows to the products
table and this is how my api/products
GET
method looks like:
public function index()
{
return ProductResource::collection(Product::all());
}
It works because when I manually type in the browser localhost:8000/api/products
the JSON object with the products is displayed.
But when I try to call the API from the Next code, I get 500 (Internal Server Error)
.
This is the product.jsx
code:
function Product({ data }) {
}
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`http://localhost:8000/api/products/`, {
method: 'GET',
mode:'cors',
})
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
export default Product
Upvotes: 0
Views: 696
Reputation: 3262
I found the issue: I just did not have any code in the render
function of the React component. I need to return something:
function Product({ data }) {
//return something here!
return (
<div>Some data</div>
)
}
//rest of the code remains the same
Upvotes: 1