Fetch fail with ERROR : POST 415 & GET 405

Fetch fail with ERROR : POST 415 & GET 405

我尝试修改这个 Microsoft.docs 示例 => Call an ASP.NET Core web API with JavaScript
我想使用 fetch POST 发送 usernamepassword,我的 AccountController 应该 return Token
在这样做之前,我已经在 POSTMAN & Swagger 上测试了我的 login API,它有效!
更新
我解决了POST ERROR 415,但是仍然有GET ERROR 405,有人能告诉我原因吗?谢谢!

我的错误: Imgur
我的测试:

{
  "username": "Genevieve",
  "password": "sss"
}
Curl

curl -X POST "https://localhost:5001/login" -H  "accept: text/plain" -H  "Content-Type: application/json" -d "{\"username\":\"Genevieve\",\"password\":\"string\"}"
Request URL https://localhost:5001/login

Server response
Code    Details
200 
Response body
Download
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJHZW5ldmlldmUiLCJqdGkiOiJmYjJhNjdlNC1hZWFjLTRkMTktOWU2ZC03NDk0ZTVmMWYwNzciLCJyb2xlcyI6IkFkbWluIiwibmJmIjoxNjI4ODM0NTcwLCJleHAiOjE2Mjg4MzgxNzAsImlhdCI6MTYyODgzNDU3MCwiaXNzIjoiYXBpMSJ9.8HqCMwAbm3KXMXTGo868dARfF1UfMC1BEniq01UfyFQ"
}
Response headers
 content-type: application/json; charset=utf-8 
 date: Fri13 Aug 2021 06:02:49 GMT 
 server: Kestrel 

我的Javascript代码:

function sendtoken(){
    const token_name = document.getElementById('token_name');
    const data = {
        username : 'Genevieve',
        password : 'sss'
    };
    fetch('login', {
        method: 'POST',
        headers: {
            'Accept' : 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        body : JSON.stringify(data)
    })
    .then(response => response.json())
    .then(() => {
        getToken();
    })
    .catch( error => console.error('Unable to send Token.', error));
}

function getToken(){
    fetch('login')
    .then(response => response.json())
    .then( data => _displayToken(data))
    .catch( error => console.error('Unable to get Token.', error));
}

function _displayToken(data){
    const final = document.getElementById('Token');
    final.innerHTML = data.token ;
    console.log(data.token);
}

我的 API :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using api1.Helpers;
using api1.Models;
using api1.ViewModels;
using Microsoft.AspNetCore.Cors;

namespace api1.Controllers
{
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly JwtHelpers helpers;

        public AccountController(JwtHelpers helpers)
        {
            this.helpers = helpers;
        }
        [EnableCors("GetPolicy")]
        [HttpPost("login")]
        public ActionResult<LoginResult> Login(Login model)
        {
            if (CheckPassword(model.Username,model.Password))
            {
                return new LoginResult(){
                    Token = helpers.GenerateToken(model.Username,"Admin",60)
                };
            }
            else
            {
                return BadRequest();
            }
        }

        private bool CheckPassword(string username, string password)
        {
            if(username == "Genevieve")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
fetch('login', {
    method: 'POST',
    headers: {
        'Accept' : 'application/json, text/plain, */*',
        'Content-Type': 'applicaiotn/json'
    },
    body : JSON.stringify(data)

正如您在代码中看到的那样,您写了 'applicaiotn/json',拼写不正确。您收到 415(不受支持的媒体)是有道理的,因为 'applicaiotn/json' 不受支持。 修正拼写错误。

405(方法不允许)是因为您在“/login”处没有支持HTTP GET(方法类型)的端点。您需要添加另一个带有 [HttpGet("login")] 的 method/endpoint。

我想这就是你要找的东西

    fetch('login', {
        method: 'POST',
        headers: {
            'Accept' : 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        body : JSON.stringify(data)
    })
    .then(response => response.json()
        .then( data => _displayToken(data)
      .catch( error => console.error('Unable to get Token.', error))))
   .catch( error => console.error('Unable to send Token.', error));