nodejs.ForbiddenError: invalid csrf token,egg中post失败解决方案

【vue2】axios请求与axios拦截器的使用详解 在vue中使用axios与axios拦截器的方法(全家桶之一) 阅读详情

问题:

前台使用axios发送Post请求,后端使用egg框架接受请求,报错nodejs.ForbiddenError: invalid csrf token。

原因:

egg 框架内置了安全系统,默认开启防止 XSS 攻击 和 CSRF 攻击,每次请求得时候请求头必须携带csrfToken字段。

解决方案:

一:关闭安全策略

在 config.default.js 文件中加入以下代码:

config.security: {
   csrf = {
     enable: false,
   }
}

但是显然这种是及其不提倡的。

二、请求头中携带csrfToken字段

server端:

// config.default.js 

config.security= {
   csrf : {
     headerName: 'x-csrf-token',// 自定义请求头
   }
}

客户端:

const getCookie = (val) => {//获取x-csrf-token字段
  var arr,reg=new RegExp("(^| )"+val+"=([^;]*)(;|$)");
  if(arr=document.cookie.match(reg))
  return unescape(arr[2]);
  else
  return null;
}

// NProgress 配置
NProgress.configure({
  showSpinner: false
});

//http请求拦截
httpNet.interceptors.request.use(function(config) {
  console.log(document.cookie);
  //发送请求之前
  config.headers['Content-Type'] = "application/json";
  config.headers['x-csrf-token'] = getCookie('csrfToken');//请求头设置x-csrf-token字段
  //开启 progress bar
  NProgress.start();

  return config;
},function(err) {
  //请求错误处理
  return Promise.reject(err);
})
Vue.js 中发起 HTTP 请求:探索各种方法及其使用技巧 在 Vue.js 项目中,发起 HTTP 请求是获取和处理数据的关键。通过本文的介绍,您应该已经了解了 Vue.js 中常见的发起 HTTP 请求的方式,包括基本使用、设置 Token 以及相关技巧。在实际应用中,根据您的需求选择合适的发起 HTTP 请求的方式,并正确使用它,可以确保您的数据获取任务能够高效地完成。 阅读详情

相关推荐

python后端的支付宝小程序用户认证问题(alipay-sdk-python、pycrypto无法安装)

python后端的支付宝小程序用户认证问题(alipay-sdk-python、pycrypto无法安装) 写在前面 事先说明,本人不是大佬,我只是在不断探索的途中找到了解决这个问题的方法,之前在网上搜索的时候没有看到相关文章,所以就来简单讲一下。 正文 借着蚂蚁金服小程序大赛开通了支付宝小程序个人开发者,尝试将一个微信小程序的项目移植到支付宝上,支付宝对于用户唯一id的获取比微信要复杂很多,微信...

weixin_43102379的博客 3643

egg.js框架post请求出现invalid csrf token安全验证的报错,已解决

不得不说阿里的egg框架做的还是相当不错的,自带安全验证。 问题: get请求正常,post请求后台就会报这样的错误。 "nodejs.ForbiddenError: invalid csrf token" 对此问题官方有说明 点击跳转egg官方安全说明 这里不做过多解释 方法一:在confit.default.js新增以下代码,表示关闭安全验证(不推荐) config.security = { csrf: { enable: false, }, }; 方法二: 在前端

qq_31676725的博客 5401

实战指南 | 快速修复Adobe Acrobat 2020安装过程中的常见注册表错误

本文提供了Adobe Acrobat 2020安装过程中遇到“无法打开键”注册表错误的详细修复指南。通过安全编辑注册表,精准定位并删除残留键值,可快速解决此常见安装报错,确保软件顺利安装。同时,文章也介绍了其他安装问题的应对策略与预防措施。

weixin_29200485的博客 562

jquery ajax post()

jquery ajax post() 应用:使用post发送异步请求,从后端获取数据 ********************* 语法:post(url,[data],[callback]) url:请求获取数据地址 data:可选,传递给后端的数据 callback:可选,请求成功后调用,请求失败不会调用,函数参数: response:请求结果 status:请求结果状态,如success xmlhttpRequest:http请求对象 type:请...

weixin_43931625的博客 548

ADNI数据集下载(详细)

刚刚接触到这个数据集的时候比较头疼,用了好长的时间才把下载过程和预处理过程弄明白。需要发送电子邮件给官方平台,收到回信后才能够下载到数据集。 1、ADNI账号注册 第一步:搜索百度打开ADNI 第二步,点击ADTA&SAMPLES 第三步:一直将鼠标往下拉 点击ADNI,进入里面填写信息。需要填写的信息还是挺多的,耐心填写,再等到邮件回复就可以了 2、ADNI数据集下载 登录申请的邮...

蜗牛遥遥 3万+

欧拉 openEuler 20.03安装配置tigervnc-server

欧拉 openEuler 20.03安装配置tigervnc-server openEuler VNC

郭亚望 8953

nodejs.ForbiddenError: invalid csrf token解决方案

【现象】 【解决方法】在 config.default.js 文件中加入以下代码: config.security = { csrf:{ enable: false, } }

一火的专栏 2281

雷电模拟器+Google Play服务配置全指南:从安装到定位问题解决

本文详细介绍了雷电模拟器配置Google Play服务的全流程,包括版本选择、组件安装、定位服务调试及网络问题排查。针对安卓开发者的常见挑战,提供从基础到高级的解决方案,帮助优化测试环境稳定性与定位精度。

weixin_30399821的博客 1236

Axios-Auth-Refresh 常见问题解决方案

Axios-Auth-Refresh 是一个开源库,用于通过 axios 拦截器实现自动刷新授权。该项目允许开发者在请求失败时轻松拦截原始请求,刷新授权,并继续执行原始请求,而无需用户察觉。它适用于处理授权令牌过期的情况,自动更新令牌并继续进行网络请求。项目主要使用 JavaScript 编程语言,依赖于 axios 库。 ## 新手常见问题及解决步骤 ### 问题一:如何安装和使用 Axio...

gitblog_00605的博客 547

大规模新闻聚合爬虫实战:Python爬取数百万新闻数据的完整指南

本文详细介绍了如何构建一个大规模新闻聚合爬虫,结合Python异步爬虫技术,实现高效、稳定的新闻数据采集。增加NLP模块对新闻内容做自动分类、情感分析。引入机器学习模型检测新闻真实性。使用分布式爬虫框架进一步提升规模。增加多媒体内容抓取与处理。

2201_76125261的博客 1554

RK3568平台开发系列讲解(中断及异常篇)中断下半部:中断线程化

以前用 work 来线程化地处理中断,一个 worker 线程只能由一个 CPU 执行, 多个中断的 work 都由同一个 worker 线程来处理,在单 CPU 系统中也只能忍着 了。少数中断不能线程化,典型的例子是时钟中断,有些流氓进程不主动让出处理器,内核只能依靠周期性的时钟中断夺回处理器的控制权,时钟中断是调度器的脉搏。中断处理线程是优先级为50、调度策略是SCHED_FIFO的实时内核线程,名称是“irq/”后面跟着Linux中断号,线程处理函数是。,说明是线程化的中断,那么唤醒中断处理线程。

内核笔记 435

Vue的三种网络请求方式

在进行 Vue 的网络请求之前,我们先写一些假数据:users.json: 1. 写法1:XMLHttpRequest发送请求 使用 XMLHttpRequest 请求 users.json 中的数据: 使用 fetch 请求 users.json 中的数据: 概述:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和node.js中。能拦截请求和响应,自动转换JSON数据。axios也是vue作者推荐使用的网络请求库。优势:使用方法: 步骤1:使用初始化 node.js 配置文件步骤

月光晒了很凉快的博客 1万+

《AI Coding手册:Claude Code、OpenAI Codex、OpenClaw深度解析与实战指南》

AI编码技术经历了从简单规则匹配到深度神经网络,再到当前智能体(Agent)架构的范式转变。第一阶段:静态代码补全(2010-2018)早期工具如IntelliSense、Emmet基于语法分析和固定模板提供代码提示。这类系统依赖预定义规则,缺乏语义理解能力,仅能处理局部代码片段。第二阶段:统计语言模型(2018-2020)以GPT-2、TabNine为代表,引入基于大规模代码训练的神经语言模型。

AI天才研究院 1033

application/x-www-form-urlencoded类型如何获取表单数据及ImmutableMultiDict如何使用

web开发中,时常会用到表单数据,利用表单自带的active字段设置url来触发一个表单请求,这个请求中会携带web页面中填写的表单数据,后台服务程序如何获取这些数据呢。通过fiddler抓包可以发现这种通过form发起的post请求,content-type类型时applicaiton/x-www-form-urlencoded,而不是常规的application/json格式,所以请求body...

zoulonglong的博客 8597

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

Gateway 解决body流重复获取,对application/json,multipart/form-data,x-www-form-urlencoded 参数加解密和 增删参数

【代码】Gateway 解决body流重复获取,对application/json,multipart/form-data,x-www-form-urlencoded 参数加解密和 增删参数。

weixin_45220510的博客 1866

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

Vue axios http Request 请求封装

Vue axios http Request 请求封装

草木疏博客 412

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Axios-Auth-Refresh:自动刷新授权的开源库

Axios-Auth-Refresh 是一个基于 JavaScript 编写的开源项目,旨在帮助开发者通过 axios 的拦截器实现自动刷新授权的功能。 ## 1. 项目基础介绍 Axios-Auth-Refresh 是一个轻量级的库,它通过 axios 的拦截器机制,自动处理因授权过期导致的请求失败问题。当请求因为授权问题失败时,该项目可以自动执行刷新授权的逻辑,并在获得新的授权后重新发送请...

gitblog_00272的博客 1065

axios-auth-refresh 使用教程

`axios-auth-refresh` 是一个用于处理 Axios 请求中 token 刷新逻辑的开源项目。它可以帮助开发者在用户访问令牌(access token)过期时,自动刷新令牌并重试失败的请求,从而提供无缝的用户体验。该项目通过 Axios 拦截器实现这一功能,确保在不影响用户操作的情况下,后台自动完成令牌的刷新和请求的重试。 ## 项目快速启动 ### 安装 首先,你需要安装 ...

gitblog_01075的博客 1115

Axios.post 请求报错: 403 Forbidden missing csrf token 和 invalid csrf token

Axios.post。

guoqkmiss的博客 3502

Vue+element Upload利用http-request实现第三方地址图片上传

vue element upload图片上传http-request方法 后端oss图片上传接口简单实现

Ron_的博客 1万+

axios刷新token

推荐一个npm库: axios-auth-refresh

Cool的博客 757

Vue体验(前后端交互)

记录:263 体验XMLHttpRequest、jquery、Promise、fetch、axios的异步方式调用后端接口。 本例环境: 后端:node.js、express。 前端:Vue.js、HTML、CSS、jQuery、axios。 方式:分别使用XMLHttpRequest、jquery、Promise、fetch、axios的异步方式调用后端接口。 Ajax:Asynchronous Javascript And XML(异步JavaScript和XML)。在网页中利用 XMLHt

zhangbeizhen18的博客 2558

Vue中XMLHttpRequest的详细使用方法

Vue中使用XMLHttpRequest(XHR)来获取数据的方式与传统的HTML页面相同。在Vue中,可以将XHR封装在methods中的方法里,然后在Vue实例中调用该方法来实现数据的获取和渲染。以下是一个简单的例子:

代码小疯子 2607

推荐使用:axios-auth-refresh,自动刷新授权的利器!

在开发Web应用时,我们经常遇到的一个问题是处理用户的授权过期问题。为了解决这个问题,我们可以利用axios库中的拦截器功能进行处理。而`axios-auth-refresh`正是这样一个工具,它能够帮助你轻松地实现在请求失败后自动刷新授权,并继续执行原请求,无需任何用户交互。 ## 项目介绍 `axios-auth-refresh`是一个基于axios的小巧且强大的库,它的核心功能是通过设置...

gitblog_00043的博客 461

vue 请求拦截器配置

vue 请求拦截器

CCKing7的博客 4232

Egg post 失败 { message: 'invalid csrf token' } 解决方案

服务端无法接受 post 请求,并且前台报错 403 ,服务端自动返回信息:message: 'invalid csrf token' 很多人的解决方案是直接在 config.default.js 文件中加入以下代码: config.security: { csrf: { enable: false, } } 以上方法确实可以解决此方案,但是不推荐,egg 框架内置了安全系...

甘宇辉的博客 2万+
上一篇: react在不暴漏配置文件的情况下配置less
下一篇: react-redux教程
TE杨
博客等级 码龄7年 56粉丝 124原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值