我使用owin中间件保护我的Web API时遇到问题.
我安装了下面的包
Install-Package Microsoft.Owin.Cors -Version 2.1.0
Run Code Online (Sandbox Code Playgroud)
以下是ConfigureAuth.cs代码.
public void ConfigureAuth(IAppBuilder app)
{
//...
app.UseOAuthBearerTokens(OAuthOptions);
///Install-Package Microsoft.Owin.Cors -Version 2.1.0
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
Run Code Online (Sandbox Code Playgroud)
我在一个链接上托管了这个WebApi项目,比如http://webaip.azurewebsites.net
我试图从另一个站点访问上述API的控制器方法,比如说,http: //mysite.azurewebsites.net上面的代码我可以调用所有不安全的API方法.(未使用Authorize属性修饰)通过javascript我无法调用/ Token进行身份验证.以下是我的javascript代码.
function LogIn() {
var loginData = {
grant_type: 'password',
username: 'username',
password: 'password',
};
$.ajax({
type: 'POST',
url: 'http://webaip.azurewebsites.net/Token/',
data: loginData
}).done(function (data) {
alert('logged in');
alert(data);
}).fail(function (data) {
alert('login problem')
}).error(function (data) {
alert('error invoking API');
});
return false;
}
Run Code Online (Sandbox Code Playgroud)
我收到了以下错误
XMLHttpRequest cannot load http://webaip.azurewebsites.net/Token/. No 'Access-Control-Allow-Origin' header is present on …Run Code Online (Sandbox Code Playgroud) 我有以下代码:
var qs = require('qs');
const ROOT_URL = 'http://localhost:56765/';
const data = qs.stringify({ username, password, grant_type: 'password' });
axios.post(`${ROOT_URL}token`, data)
.then(response => {
debugger;
dispatch(authUser());
localStorage.setItem('token', response.data.token);
})
.catch((error) => {
debugger;
dispatch(authError(error.response));
});
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,我点击调试器并且错误对象Error: Network Error at createError (http://localhost:3000/static/js/bundle.js:2188:15) at XMLHttpRequest.handleError (http://localhost:3000/static/js/bundle.js:1724:14)在catch块中.但是,在Chrome的网络标签中,状态代码为200,但是当我点击此请求的响应/预览标签时,没有数据.如果我点击继续,我实际上会按预期在响应/预览选项卡中获取令牌和其他数据,但此时它已经到达了catch块,因此不会点击then块.
我甚至调试了后端,它没有发回错误,所以我认为这是一个前端错误.有谁知道是什么原因造成的?
编辑:
只是为了添加更多细节,如果我将请求更改为使用fetch而不是axios,我会收到不同的错误TypeError: Failed to fetch.用于呼叫的代码是:
fetch(`${ROOT_URL}token`, {
method: 'POST',
body: data
})
Run Code Online (Sandbox Code Playgroud)