Home > Back-end >  NodeJS server performs POST request, but returns HTTPErrorResponse
NodeJS server performs POST request, but returns HTTPErrorResponse

Time:01-04

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?

CodePudding user response:

The server could return successfully, however the callback function CreateData was expecting a JSON object to be returned from the server. Because the string returned is not JSON, an HTTPErrorResponse was thrown. The solution is to change the string returned from my server to a JSON object, 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({}) // returns successfully, no error
    })

  •  Tags:  
  • Related