JS Fetch API 不适用于具有 Authorize

我在客户端有以下代码:


fetch("/music/index", { headers: { "Content-Type": "application/json" } })

    .then(response => {

        if (!response.ok) {

            throw response;

        }

        return response.json();

    })

    .then(json => {

        console.log("Done! It's all good");

    })

    .catch(response => console.log(response));

不幸的是,这甚至没有到达MusicController(服务器端),它看起来如下(为了说明这一点而进行了简化):


[Authorize]

public class MusicController : Controller {

    public async Task<IActionResult> Index() {        

        IEnumerable<Song> songs = await _songsRepository.GetAll();

        return Json(songs);

    }

}

从我在开发者控制台中看到的我被重定向到 /Account/Login?returnUrl...


同时,使用 jquery api,一切似乎都正常:


$.get("/music/index")

    .done(json => console.log("Done! It's all good"))

    .fail(error => console.log(error));

我怀疑我没有正确设置我的标题?不确定在网上找不到任何东西。此外,此(或非常相似)代码用于在以前(非核心)版本的 ASP.NET 中工作。

阿晨1998
浏览 208回答 1
1回答

慕莱坞森

您需要在提取中设置凭据选项,这将执行以下操作:Request 接口的凭据只读属性指示用户代理是否应该在跨域请求的情况下发送来自其他域的 cookie。这类似于 XHR 的 withCredentials 标志,但具有三个可用值(而不是两个)omit: 永远不要发送cookies。same-origin:如果 URL 与调用脚本来自同一来源,则发送用户凭据(cookie、基本 http 身份验证等)。这是默认值。include:始终发送用户凭据(cookies、基本的 http 身份验证等),即使是跨域调用。来源你的 fetch 现在看起来像这样:fetch("/music/index", {&nbsp;&nbsp; headers: { "Content-Type": "application/json" },&nbsp; credentials: 'include'})&nbsp; .then(response => {&nbsp; &nbsp; &nbsp; if (!response.ok) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw response;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return response.json();&nbsp; })&nbsp; .then(json => {&nbsp; &nbsp; &nbsp; console.log("Done! It's all good");&nbsp; })&nbsp; .catch(response => console.log(response));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript