【发布时间】:2022-01-23 19:25:09
【问题描述】:
您好,我想将数据提交到服务器时遇到问题。这是我的代码:
Service.ts:
@Injectable({providedIn: 'root'})
export class ArticlesService {
constructor(private http: HttpClient) { }
createArticle(title: string, body: string, categoryId: number) {
const postData: Article = { title: title, body: body, categoryId: categoryId};
const url = 'http://18.192.182.140/api/articles?api_token=9aK4W3D7NpbWwPzJmUOIcyPmyehl0PHZLWP14rzQqKzUPtcFCo0Tn051CvwN';
return this.http.post(url, postData)
}
}
模型.ts:
export interface Article {
title: string;
body: string;
categoryId: number;
}
ArticleComponent.ts:
@Component({
selector: 'app-new-article',
templateUrl: './new-article.component.html',
styleUrls: ['./new-article.component.css']
})
export class NewArticleComponent implements OnInit {
constructor(private articleService: ArticlesService) { }
ngOnInit(): void { }
createNewArticle(postData: Article) {
this.articleService.createArticle(postData.title, postData.body,
postData.categoryId).subscribe(responseData => {
console.log(responseData);
});;
}
Article.html:
<div class="container">
<h1>Add New Article</h1>
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<form #postForm="ngForm" (ngSubmit)="createNewArticle(postForm.value)">
<div id="user-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" class="form-control">
</div>
<div class="form-group">
<label for="body">Body</label>
<input type="text" id="body" class="form-control">
</div>
<div class="form-group">
<label for="category_id">Category ID</label>
<input type="number" id="category_id" class="form-control">
</div>
</div>
<button class="btn btn-primary" type="submit">Add new Article</button>
<button class="btn btn-primary" type="button" routerLink="/admin">Cancel</button>
</form>
</div>
当我点击“添加新文章”按钮时,我收到此错误:
ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: 'OK', url:
'http://18.192.182.140/api/articles?api_token=9aK4W…
WwPzJmUOIcyPmyehl0PHZLWP14rzQqKzUPtcFCo0Tn051CvwN', ok: false, …}
任何人都知道如何解决这个错误,我尝试将 responseType 设置为“text”,但它不起作用。谢谢!
【问题讨论】:
-
设置带有标头的 api 令牌
-
您对服务器有控制权吗?是否有任何服务器日志信息可以帮助您?是否有任何(招摇)文件?
-
我没有看到错误。响应的代码为 200(OK)。它应该是 201,但这是来自服务器。好像是服务器端的问题。
标签: angular post error-handling