未在angular6

时间:2018-12-01 16:07:38

标签: node.js angular express angular6 x-xsrf-token

我的angular 6和nodeJS网络应用程序出现了一些奇怪的问题。

我必须实现csrf保护,所以我已经在节点js中实现了csurf,下面给出了我的节点js代码,

let express=require('express');
let app=express();

var cookieParser = require('cookie-parser')
csrf = require('csurf');
//import body parser
let bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin","*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,X-XSRF-Token");
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header('Access-Control-Allow-Credentials', true);
  next();
});
app.use(cookieParser('ksdnfjn9834f80sa9asjfasdj'));
app.use(csrf({ cookie: true }));
app.use(function(req, res, next) {
  console.log(req.csrfToken());

  res.cookie('XSRF-TOKEN', req.csrfToken(),{ httpOnly: false,Path:"/" });
  return next();
});
app.use('/api',apiRoutes);
app.use('/admin',adminapiRoutes);

app.listen(3000,function(){
    console.log('api is listening on port'+3000);
})

我的有角js代码看起来像这样,以调用api发布请求,

this.http.post(this.contact_api_url, {
      "name": this.contact_name,
      "email": this.contact_email,
      "message": this.contact_message
    },{withCredentials: true,headers: new HttpHeaders().set('X-XSRF-TOKEN', "token_get_in_cookie" ) }).subscribe((val) => {
      this.renderer.removeClass(loda_element,'show');
      //var msg=JSON.stringify(val);
      alertify.success(val['message']);
      this.contact_name = '';
      this.contact_email = '';
      this.contact_message = '';
      grecaptcha.reset();
      this.captcha_response = '';

    }, error => {
      this.renderer.removeClass(loda_element,'show');
      alertify.error("Error Occurred. Try Again.");
    });

现在的问题是,它没有以任何方式设置标头,甚至没有添加任何我也在导入中的代码下面添加的其他标头

HttpClientXsrfModule.withOptions({
      cookieName: 'XSRF-TOKEN',
      headerName: 'X-XSRF-TOKEN'
    }),

但没有任何效果,因为它没有添加X-XSRF-TOKEN标头,我还实现了以下拦截器,

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let requestToForward = req;
        let token = this.tokenExtractor.getToken() as string;
        const headers: any = {};

        if (token !== null) {
            headers['X-XSRF-TOKEN'] = token; // add it to the header

            requestToForward = req.clone({ setHeaders: headers });
        }
        return next.handle(requestToForward);
    }

我还获得了令牌值,该值由XSRF-TOKEN中的节点js代码设置,但标头未设置。

任何人都可以知道为什么未在角度6中设置标头吗? 注意:我在localhost上工作,所以nodeJS在http://localhost:3000上运行,而angular在http://localhost:4200上运行

0 个答案:

没有答案
相关问题