如何解决ReactJS-所请求的资源上没有“ Access-Control-Allow-Origin”标头
我正在尝试通过asp.net Web API 2对用户进行身份验证并生成令牌。当我使用邮递员发送请求时,它将生成令牌。但是当我使用Reactjs和Axios发送请求时,它给了我一个错误。
CORS策略已阻止从原点“ http:// localhost:3000”访问http:// localhost:4093 / token处的XMLHttpRequest:请求中不存在“ Access-Control-Allow-Origin”标头资源。
错误:网络错误 在createError(createError.js:16) 在XMLHttpRequest.handleError(xhr.js:83)
获取http:// localhost:4093 / token net :: ERR_Failed
我在WebApiConfig.cs中启用了cors,并将标头添加到ApplicationOAuthProvider.cs
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
EnableCorsAttribute cors = new EnableCorsAttribute("*","*","*");
config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
);
}
}
ApplicationOAuthProvider.cs
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] { "*" });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName,context.Password);
if (user == null)
{
context.SetError("invalid_grant","The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity,properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
login.js
submitCredential = user => {
const qs = require('querystring')
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
}
const data = { username: user.Email,password: user.Password,grant_type: 'password' };
axios.get('http://localhost:4093/token',qs.stringify(data),config)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。