因此,我正在使用帶有 ASP.Net Core 的 Entity Framework 作為后端和 AngularJS 作為前端來制作一個簡單的筆記應用程式。
預期的行為是,當應用程式啟動時,它應該加載已經保存在我的資料庫(MySQL)中的筆記串列
事情是,當我的應用程式執行 Get 請求時,它會重新啟動以下錯誤:
在此之前,我遇到了一個 CORS 問題,我通過添加http://
到我的連接字串中解決了這個問題,在解決了這個問題之后,我得到了這個。我一直在尋找整個互聯網,但我似乎沒有找到答案。
這是我的note.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Note } from '../note';
@Injectable({
providedIn: 'root'
})
export class NoteService {
private url: string = "http://localhost:44353/api/NotesLists";
constructor(private http: HttpClient) { }
getNotes(): Observable<Note[]> {
return this.http.get<Note[]>(this.url);
}
}
這是我的家庭組件(我訂閱以獲取回應):
import { Component, OnInit } from '@angular/core';
import { NoteService } from '../services/note.service';
import { Note } from '../note';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
public notes: Note[] = [];
constructor(private noteService: NoteService) { }
ngOnInit(): void {
this.noteService.getNotes()
.subscribe(data => this.notes = data);
}
}
還有我[HttpGet]
對 .Net Core 的要求
[HttpGet]
public IActionResult Get()
{
try
{
var response = _datacontext.NotesList
.Include(notesList => notesList.Note)
.ToList();
if (response.Count == 0)
{
return NotFound();
}
return Ok(response);
}
catch (Exception e)
{
return StatusCode(500, e.Message);
}
}
還有我DataContext
的更好的背景(哈!)
using Microsoft.EntityFrameworkCore;
using noteAppAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace noteAppAPI.Helpers
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> option) : base(option)
{
}
public DbSet<NotesList> NotesList { get; set; }
public DbSet<Note> Notes { get; set; }
}
}
uj5u.com熱心網友回復:
感謝@MarkHomer 在評論中提出的建議。解決方案是:
更改連接字串note.service.ts
從
private url: string = "http://localhost:44353/api/NotesLists";
至
private url: string = "http://localhost:44353/api/NotesLists";
這將導致我必須在我的 API 中啟用 CORS,以便 HTTPS 請求能夠正常作業。
Startup.cs
要在add inConfigureServices
方法中啟用 CORS :
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.AddDbContext<DataContext>(option => {
option.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
并且Configure
在同一個檔案中的方法中:
app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/497712.html