【问题标题】:Unable to send http post with credentials to iis node server无法将带有凭据的 http 帖子发送到 iis 节点服务器
【发布时间】:2019-02-08 11:50:13
【问题描述】:

我正在尝试使用用户凭据从我的 Angular 应用程序向我的 node.js 服务器发送一个 http post 请求,以便记录它。 两者都托管在 IIS(具有 nodeiis 的节点服务器)中,并且都配置为通过 windows 身份验证进行身份验证。

我的角码:

var url = "http://myurl:15001/addItem";
this.http.post(url, {
    "itemName": "SomeName",
    "itemColor": "SomeColor"
}, {withCredentials: true}).subscribe(res =>{
    console.log("Great, item was added");
})

我的 Node.js 代码:

var app = express();
var allowCrossDomain = function (req, res, next){
res.header('Access-Control-Allow-Origin', "http://myurl") //Cannot be a wildcard because of the credentials.
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

if(res.method == 'OPTIONS')
    res.send(200);
else
    next();
};
app.use(allowCrossDomain);

app.post('/addItem', function(req, res){
    //Saves the item...

    res.setHeader('Access-Control-Allow-Origin', 'http://myurl')
    res.status(200);
    res.send(true);
});

当我发出请求时,控制台出现以下错误:

选项http://myurl:15001/addItem 401(未授权)

XMLHttpRequest 无法加载 http://myurl:15001/addItem。回应 预检未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此,Origin 'http://myurl' 是 bot 允许访问的。这 响应的 HTTP 状态代码为 401。

当我尝试对我的 http get 请求做同样的事情时,一切正常,我得到了结果。 当我为每个 OPTIONS 请求发送 200 个代码时,我不知道为什么我的 OPTIONS 请求未经授权。

我尝试使用 cors node.js 包但没有帮助,也许我没有使用正确。

谁能解释我如何解决这个问题并让我的 http 帖子通过预检?非常感谢!

【问题讨论】:

标签: node.js angular express iis cors


【解决方案1】:

如果您使用的是 Angular 6,它支持 proxy.conf,它将代理后端 API URL。更多详情,这里是链接https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

【讨论】:

  • 你知道没有代理解决这个问题的其他方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 2011-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多