__RequestVerificationToken not sent correctly with axios 0.17.1 and MVC 3/4/5

Viewed 2150

I eliminated jQuery from the project in favor of axios, but when I try to validate the __RequestVerificationToken, the controller responds with:

The required anti-forgery form field "__RequestVerificationToken" is not present

I see that the data is sent in json format and with jquery as form data.

Is there any way for the Controller to detect the json format or do I need to serialize the data before sending it?

axios({
      url: '/api/controller/method',
      data: {
        __RequestVerificationToken,
        otherData
      },
      method: 'post'
    })
2 Answers

We add a config file for axios and add a plugin "qs" to stringify the query.

import qs from 'qs'
import axios from 'axios'
import fd from '../FormDataBuilder'

axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.paramsSerializer = p => qs.stringify(p, { allowDots: true })
axios.defaults.transformRequest = [d => typeof d === 'object' ? d.formdata ? fd(d) : qs.stringify(d, { allowDots: true }) : d]

export default axios

The FormDataBuilder is a function for the case of "formdata" forms.

Now the server receive the token correctly.

Add qs to your project (npm install qs --save)

in your .chtml :

<div id="token">@Html.AntiForgeryToken()</div>

in your component vue.js :

at the start:

import qs from 'qs'
import axios from "axios"

in the function:

let token = document.querySelector('token, input').getAttribute('value');   

axios.post( "/api/controller/method", qs.stringify({ '__RequestVerificationToken': token}));
Related