axios post method 400 bad request - javascript

I'm getting a JSON file, editing it and trying send it back to server. But when I use post method it throws an error 400 bad request.In response shows "no template_id or no template_json presented". What could be the problem?
saveData() {
const { data } = this.state
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}

Please try to use this:
data.template_id = 1;
saveData() {
const { data } = this.state
data.template_id = 1;
let token = localStorage.getItem("token")
axios
.post(
"http://dev.candidates.hrmessenger.com/stage/set-template",
data,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
},
)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
You missed the parameter template_id, or you need to ask from your API developer to send the documentations of the POST Method API.

Related

Getting erorr Cannot POST /undefined/signup

I can sign up a user via postman. But when I use my app I am getting that error. My signup method is ok. But my fetch address is not good. here is method.
export const signup = user => {
return fetch(`${API}/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
};
const API = process.env.REACT_APP_API_URL;

How to make a fetch request to TinyURL?

I am trying to make a fetch request specifically a post request to tinyURL to shortern a url generated on my site. here is the tinyURL API
Currently, I am writing my code like this but it doesn't appear to be returning the short url.
the word tinyurl seems to be banned within links so all links
containing the word tinyurl have been replaced with "SHORT"
here is the tinyURL API https://SHORT.com/app/dev
import * as React from 'react'
interface tinyURlProps { url: string } export const useTinyURL = ({ url }: tinyURlProps) => { React.useEffect(() => {
const apiURL = 'https://api.SHORT.com/create'
const data = JSON.stringify({ url: url, domain: 'tiny.one' })
const options = {
method: 'POST',
body: data,
headers: {
Authorization:
'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
Accept: 'application/json',
'Content-Type': 'application/json',
},
} as RequestInit
fetch(apiURL, options)
.then((response) => console.log(response))
.then((error) => console.error(error))
console.log('TinyUrl ran') }, [url])
}
The snippet below seems to work
const qs = selector => document.querySelector(selector);
let body = {
url: `https://stackoverflow.com/questions/66991259/how-to-make-a-fetch-request-to-tinyurl`,
domain: `tiny.one`
}
fetch(`https://api.tinyurl.com/create`, {
method: `POST`,
headers: {
accept: `application/json`,
authorization: `Bearer 2nLQGpsuegHP8l8J0Uq1TsVkCzP3un3T23uQ5YovVf5lvvGOucGmFOYRVj6L`,
'content-type': `application/json`,
},
body: JSON.stringify(body)
})
.then(response => {
if (response.status != 200) throw `There was a problem with the fetch operation. Status Code: ${response.status}`;
return response.json()
})
.then(data => {
qs(`#output>pre`).innerText = JSON.stringify(data, null, 3);
qs(`#link`).href = data.data.tiny_url;
qs(`#link`).innerText = data.data.tiny_url;
})
.catch(error => console.error(error));
body {
font-family: calibri;
}
<p><a id="link" /></p>
<span id="output"><pre/></span>

Axios request returns 401 despite having an authorization header

I'm trying to patch data to a django API using axios using this snippet:
nextQuestion = () => {
if (this.state.currentIndex === 0) return;
const token = this.props.token;
const configs = {
headers: {
Authorization: `Token ${token}`,
},
data: {
quiztaker: this.state.data[0].quiz.quiztakers_set.id,
question: this.state.data[0].quiz.question_set[this.state.currentIndex]
.id,
answer: Number(this.state.answer),
},
};
console.log(configs);
axios
.patch("/api/save-answer/", configs)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
this.setState({
currentIndex: this.state.currentIndex - 1
});
};
I have confirmed that the token does indeed exist and that it is authorised to access and make changes to that endpoint through insomnia. Did i do anything wrong with how i set up axios? or is there something else i'm not getting? Apologies if it's an obvious mistake, still quite new to react.
With axios.patch() it should be executed axios.patch(url, data, config)....
const data = {
"quiztaker": this.state.data[0].quiz.quiztakers_set.id,
"question": this.state.data[0].quiz.question_set[this.state.currentIndex].id,
"answer": Number(this.state.answer),
};
const token = this.props.token;
const configs = {
"headers": {
"Authorization": `Token ${token}`,
},
};
axios
.patch("/api/save-answer/", data, configs)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});

Axios can't send credentials

I'm trying to include credentials to my requests
I'm using axios but axios don't send credentials with request.
This is how i do it with axios.
const axiosConfig = {
withCredentials: true,
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
};
axios
.get("someurl" + data, axiosConfig)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
But when i try it with fetch everything work.
fetch("someurl" + data, {
credentials: "include"
})
.then(function(response) {
return response.json();
})
.then(result => {
console.log(result);
});
how make it work with axios too?
You should see the auth parameter inside the axios config object
auth: {
username: 'janedoe',
password: 's00pers3cret'
}
see https://github.com/axios/axios

Axios get request response with 403 error forbidden

I'm new in react . Trying to make "get" request and getting 403 error forbidden, "Response for preflight does not have HTTP ok status.". In network tab in Request Method instead of "get" method shows "options". What could be the problem? Cors already open , problem with token
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer + ${token}`,
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
that's how I'm saving token. May be I'm not correctly saving it in localStorage? But when console.log it displays fine
event.preventDefault()
const formdata = new FormData()
formdata.append("username", this.state.userLogin.email)
formdata.append("password", this.state.userLogin.password)
axios
.post("http://dev.****************/get-token", formdata)
.then(res => {
if (res.data) {
console.log(res.data)
localStorage.setItem("token", res.data.access_token)
localStorage.setItem("updToken", res.data.update_token)
this.props.history.push("/settings")
}
})
.catch(error => {
console.log(error)
})
I see a problem in your Bearer token
you write it:
Authorization: `Bearer + ${token}`
but it should be :
Authorization: `Bearer ${token}`,
and the full answer is :
let token = localStorage.getItem("token")
axios
.get("http://dev.*****************get-template", {
headers: {
Authorization: `Bearer ${token}`, //here remove + in template litereal
},
})
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
Do it like this:
let token = localStorage.getItem("token")
axios.defaults.headers.common['Authorization'] = token
axios
.get("http://dev.*****************get-template")
.then(res => {
console.log("Success")
})
.catch(error => {
console.log(error)
})
This is due to CORS issue.
To solve this you need to set Access-Control-Allow-Origin header on your server side, allowing the domain from which you are sending the request or you can set it to *

Categories

Resources