Express-React | It throws me an error if I try to access using an external json file

Express-React | It throws me an error if I try to access using an external json file
0

#1

It throws me an error if I try to access using an external json file. Why is that?

Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0
(anonymous function)
src/components/customers.js:14
  11 | 
  12 | componentDidMount() {
  13 |   fetch('/api/customers')
> 14 |     .then(res => res.json())
  15 |     .then(customers => this.setState({customers}, () => console.log('Customers fetched...', customers)));
  16 | }
  17 |
const express = require('express');
//const customers = require('./customers.json');
const app = express();

app.get('/api/customers', (req, res) => {
  const customers = [
    {id: 1, firstName: 'John', lastName: 'Doe'},
    {id: 2, firstName: 'Brad', lastName: 'Traversy'},
    {id: 3, firstName: 'Mary', lastName: 'Swanson'},
  ];

  res.json(customers);
});

const port = 5000;

app.listen(port, () => `Server running on port ${port}`);

I left this project untouched. I’ve only added a new json file and I wanted to use an external file instead of it being created locally.


#2

Removing the brackets worked.
[
{id: 1, firstName: ‘John’, lastName: ‘Doe’},
{id: 2, firstName: ‘Brad’, lastName: ‘Traversy’},
{id: 3, firstName: ‘Mary’, lastName: ‘Swanson’},
] but didn’t solve the problem.