3
votes

I am using @nrwl/Nx to create a project.

I successfully add both Angular & Nest projects to it.

I then try to test the connection between the two.

Angular code

content;

testEndpoint() {
  this.http.get<any>('api/test').subscribe(res => this.content = res);
}

Nest code

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('test')
  testConnection(): string {
    return 'Some content';
  }
}

As seen, I am simply trying to return a string from the endpoint. In the documentation,

Using this built-in method, when a request handler returns a JavaScript object or array, it will automatically be serialized to JSON. When it returns a string, however, Nest will send just a string without attempting to serialize it. This makes response handling simple: just return the value, and Nest takes care of the rest.

So naturally, I would expect this to work (their exemple is basically the same as this).

But I am met with the following error :

error: SyntaxError: Unexpected token S in JSON at position 0 at [...]

Even though the HTTP code is 200 and the content can be seen in the network tab.

Could someone explain to me what's the issue ?

(I have tried adding a content type header to the request, but to no success)

EDIT 1 : the request :

enter image description here

1
Could you check the headers of the response? If client considers it to be JSON (and it's apparently not; JSON-ed string starts from " character), either client ignores the mime-type or server still sets it to 'application/json' (or something like that). - raina77ow
Try changing it to http.get<string>, since that's what you're expecting. - Heretic Monkey
@raina77ow I have uploaded the full request as an image to my question - user4676340
@HereticMonkey not working - user4676340
@raina77ow the content type header is misleading, but to let you know, after adding @Header('Content-Type', 'text/plain') to Nest, it still doesn't work, the header gets removed. - user4676340

1 Answers

3
votes

Looks like HttpClient just ignores the content type sent by server, attempting to always treat the response as JSON. That's weird, but thankfully, you can override it specifying the expected responseType explicitly, as mentioned in the docs.

this.http.get('api/test', {responseType: 'text'})

The caveat is that you'll have to drop the generics part (or erase the type in some other way) because of this issue.

The generic MUST not be used when responseType is specified to something other than 'json' because typeof T will then be inferred automatically.