in

NodeJS server performs POST request, but returns HTTPErrorResponse


I’m using Angular’s HttpClient to perform a POST request to my NodeJS server, like so:

createData(data:any):Observable<any> {
    // verifying the content type is need to ensure the JSON object is sent as
    // JSON object to NodeJS server 
    const options = {
      headers: new HttpHeaders({
          'Content-Type': 'application/json',
      })
  };
  // This still throws an HTTPResponse error,  - 
  // SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse
    return this._http.post(`${this.apiUrl}`, data, options);
  }

And my server’s POST function is set up like so:

router.post('/', async (req,res) => {
        const body = req.body;
        await database.execute(`
            INSERT INTO Post (
                title,
                body,
                date_added
            ) VALUES (
                @title,
                @body,
                NOW()
            )
            `, {
                title: body.title,
                body: body.body,
            })
        res.end('Added post')
    })

When createData is called, the POST method is performed (I checked the Network panel in dev tools, the response “Added post” is returned from the server, and my json object is sent as the payload), but the console still returns this HTTPErrorResponse:

SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:7508:51) at ZoneDelegate.invokeTask (ht..

What could be the cause of this error, if the server function has returned successfully?



Source: https://stackoverflow.com/questions/70535248/nodejs-server-performs-post-request-but-returns-httperrorresponse

10 cheap or free ways to make your old PC run faster thumbnail

10 cheap or free ways to make your old PC run faster

Consistent hashing with bounded loads in Golang