我如何得到错误消息,我抛出从服务器在angular

本文关键字:服务器 angular 何得 错误 消息 | 更新日期: 2023-09-27 18:09:04

我有一个angular应用程序,它发送一个登录请求到服务器,并得到一个错误,我从服务器抛出的情况下,用户名或密码无效或不正确。无论如何,我在$http服务上有一个函数来获取错误消息,但由于某种原因,错误消息是一长串HTML标签,我抛出的异常是在HTML中的某个地方。我希望能够获得原始消息,而不需要自定义或任何你称之为服务器或浏览器所做的事情。

我很感激你的帮助。

更新:

我的错误是我在服务器上抛出异常而不是返回错误。现在我修复了它,我返回错误,但我想也返回一个状态码或一些适当的"http响应消息"。SetError方法不允许我这样做。还有别的办法吗?

我的方法是:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
        using (AuthRepository _repo = new AuthRepository())
        {
            bool user = _repo.Authenticate(context.UserName, context.Password);
            if (user == false)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));
        context.Validated(identity);
    }

我如何得到错误消息,我抛出从服务器在angular

理论上你可以这样使用$http:

$http.post(url, payload, config)
    .then(function success(response) {
        // do successful stuff here  
    },
    function err(response) {
        // response.data - find error message here
        // response.status - find error code here 
        // treat error here
    });

更多信息请点击这里。

然而,听起来你可能有一个服务器端问题,关于你回应客户端的方式。也许一些代码会对解决你的问题有用。

LE:关于你的状态码问题,看看这个stackoverflow问题,也许你可以弄清楚如何在你的代码库中应用它。

从我可以看到你应该有一个Response属性在你的context,你可以设置一个StatusCode。确保你阅读了所有的答案,因为我不是c#开发人员,我只是在谷歌上查了一下。