I am trying to send a form to an endpoint but I get an error forbidden 403, and I already tried with an api test and the endpoint works perfectly
const SendData = (event) => {
event.preventDefault();
let respuestasUSer = new FormData();
respuestasUSer.set('curso', state.curso)
respuestasUSer.set('nombre', state.nombre)
respuestasUSer.set('q1', state.Pregunta1)
respuestasUSer.set('q2', state.Pregunta2)
respuestasUSer.set('q3', state.Pregunta3)
respuestasUSer.set('q4', state.Pregunta4)
respuestasUSer.set('q5', state.Pregunta5)
respuestasUSer.set('q6', state.Pregunta6)
respuestasUSer.set('q7', state.Pregunta7)
respuestasUSer.set('q8', state.Pregunta8)
axios({
method: "post",
url: "https://covid.cit0.com/guardar/encuesta/",
data: respuestasUSer,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
}
In the api test I do it like this and it works for me, how could I pass this same content to axios?
CodePudding user response:
If you are using react as front end
first you set onchange event in input text field like
<form>
<input type="text" name="first_name" placeholder="first name" onChange={handlechange} />
Create
define that handlechange function like
function handlechange (e) {
const {name,value} = e.target
setstate({...state,[name]:value})
}
//before that want to define state like const [state, setstate] = useState({})
then define handleclick function like
function handleclick (e) {
e.preventDefault()
axios.post('/super_admin/newuser',state).then((res)=>{
console.log(res.data)
}).catch(err=>{
console.log(err.response.data)
})
}
here is the full code
import {useState, } from 'react'
import axios from 'axios'
export default function Newuser() {
const [state, setstate] = useState({})
function handlechange (e) {
const {name,value} = e.target
setstate({...state,[name]:value})
}
function handleclick (e) {
e.preventDefault()
axios.post('/your api',state).then((res)=>{
console.log(res.data)
}).catch(err=>{
console.log(err.response.data)
})
}
return (
<div>
<form>
<input type="text" name="first_name" placeholder="first name" onChange={handlechange} />
<button onClick={handleclick}>Create</button>
</form>
</div>
)
}
CodePudding user response:
for sending form data you can edit handleclick function to something like this
function handleclick (e) {
e.preventDefault()
const fd = new FormData()
fd.append('first_name',state.first_name)
axios.post('/your api',fd).then((res)=>{
console.log(res.data)
}).catch(err=>{
console.log(err.response.data)
})
}