我在 Angular 6 和 nodeJS Web 应用程序中遇到了一些奇怪的问题。
我必须实现 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);
})
我的 Angular js 代码如下所示,调用 api post 请求,
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上运行