zone.js:2969已通过CORS策略阻止对XMLHttpRequest的访问

Hik*_*ndo 1 express angular

我正在使用Angular连接RestAPI。我有一个错误

zone.js:2969从源' http:// localhost:4200 ' 到'localhost:8000 / auth / api / authen'处对XMLHttpRequest的访问已被CORS策略阻止:协议方案仅支持跨源请求:http,数据,chrome,chrome扩展名,https。

但这是我的POSTMAN结果, 在此处输入图片说明

这是我的Nodejs代码

const express    = require('express');
const app        = express();
const bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8000;

var router = express.Router();

app.all('*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'DELETE, HEAD, GET, OPTIONS, POST, PUT');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.use('/', router);

router.get('/api', function(req, res, next) {
    res.json({ message: 'hello' });
});

router.post('/auth/api/authen', function(req, res, next){

  res.json({
    success : true,
    result : req.body
  });

});

// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);
Run Code Online (Sandbox Code Playgroud)

private options = { headers: new HttpHeaders().set('Content-Type', 'application/json') }

  login(username:string, password:string, ipaddress:string ) : Observable<any> {
    return this.http.post<any>( this.baseUrl + '/auth/api/authen', { username, password, ipaddress }, this.options )
      .pipe(
        map(res => {
          console.log(res);
          return res;
        })
      );
  }
Run Code Online (Sandbox Code Playgroud)

一切似乎都很简单,但是我无法从Angular应用程序向服务器发送请求。请帮忙。谢谢。

Vad*_*adi 5

该错误表明,由于某种原因,请求已作为localhost:8000 / auth / api / authen发送,协议方案不支持该请求:

zone.js:2969从>起源' http:// localhost:4200 '的'localhost:8000 / auth / api / authen'访问XMLHttpRequest 已被CORS策略阻止:跨源>仅协议方案支持请求: http,数据,chrome,chrome->扩展名,https。

如果将请求更改为http:// localhost:8000 / auth / api / authen,该错误将消失。