I am getting really weird behavior trying to call the Controller in .net 5 MVC project from the angular 12.
I am getting 200 status code and even get the data that I suppose to get but at the same response I am getting the error message **"Unexpected token e in JSON at position 0"**.enter image description here
I am able to use the postman and call the controller with no problem so that makes me think the problem is with the Angular.
Here is how my angular side looks like:
data.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Token } from './models/token';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService{
constructor(private http: HttpClient) { }
getEco(input:string):Observable<string>{
return this.http.get<string>(`home/${input}`,{ headers: this.headers});
}
getToken(): Observable<Token> {
return this.http.post<Token>("token/generate", {headers: this.headers })
}
private headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json' });
component:
import { Component, OnInit } from '@angular/core';
import { DataService } from './data-service.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'ClientApp';
constructor(private dataService: DataService){}
ngOnInit(): void {
this.dataService.getEco("ahanahui").subscribe((res) =>{
console.log(res);
});
this.dataService.getToken().subscribe(res => console.log(res));
}
}
CodePudding user response:
I'm not sure, but I guess that, as you are coding getToken as POST instead of a a GET method, you have to send a body, or at least add a null as a "second" parameter in the http call, like this:
return this.http.post<Token>("token/generate", null, {headers: this.headers })
CodePudding user response:
I was missing the NewtonsoftJson that would serialize response for me newtonsoft.com/json
public static class ConfigurationExtensions
{
public static IServiceCollection ConfigureMVC(this IServiceCollection services)
{
services.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
return services;
}
}
