我在嘗試從角度 12 呼叫 .net 5 MVC 專案中的控制器時遇到了非常奇怪的行為。我得到了 200 個狀態代碼,甚至得到了我想得到的資料,但在相同的回應中我得到了錯誤訊息**"Unexpected token e in JSON at position 0"**。在此處輸入影像描述
我可以使用郵遞員并毫無問題地呼叫控制器,因此我認為問題出在 Angular 上。
這是我的棱角側的樣子:
資料服務.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' });
零件:
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));
}
}
uj5u.com熱心網友回復:
我不確定,但我想,當您將getToken編碼為 POST 而不是 aa GET 方法時,您必須發送一個正文,或者至少在 http 呼叫中添加一個 null 作為“第二個”引數,就像這樣:
return this.http.post<Token>("token/generate", null, {headers: this.headers })
uj5u.com熱心網友回復:
我錯過了 NewtonsoftJson,它將為我序列化回應 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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413242.html
標籤:
