I'm trying to construct my axios to be able to mimic the postman request but failed. Please help to have a look
const ax = axios.create({
timeout: 30000,
headers: {
'content-type': 'application/x-www-form-urlencoded'
}
});
// Attempt register operation
ax.post('https://url/5bc9ff9628d79b6d274165da/update.json', {
body: JSON.stringify({
json: JSON.stringify({ "stat": "Delivered" })
})
})
.then(({ data }) => {
console.log('DEBUG::success!!! data::', data);
})
.catch((err) => {
console.log('DEBUG::err', err);
});
You can make use of the code-generation feature in Postman.
Click on Code (below Save button) > Search for 'Axios' > NodeJS - Axios
Docs for code generation in Postman: https://learning.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets/
2022 Update
Click on </> icon in right side nav bar
Select Axios from drop down
Related
const addProdFunc = () => {
const proheader = {
"Content-Type": "multipart/form-data",
Authorization: `Bearer ${token}`,
};
axios
.post(
process.env.REACT_APP_ADMIN_API_URL + "product/",
{
image_path: pimg,
product_img: simg[0],
},
{
headers: proheader,
}
)
.then((response) => {
console.log(response);
});
};
I tried a single image it works but when I try to upload multiple images it doesn't upload.
when I put in the console image data comes like this.
same code for both fields in the backend.
You need to make sure that your API expects one or more images. You seem to get the images correctly from the front-end side but the back-end is not expecting that.
I'm quite new to react and have an issue that i'm not sure whats wrong.
I have one external api with an endpoint that contains articles and another endpoint to get the images thats connected with the articles. I want to display the articles and the images together, but I can't get the images to show.
The flow is as follows:
First I find the article with the article api endpoint and the article id. And it looks like this:
const { itemId } = useParams()
const [article, setArticle] = useState([])
const [articleImg, setArticleImg] = useState('')
const [fileId, setFileId] = useState('')
useEffect(() => {
fetch(`https://api.fortnox.se/3/articles/${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
console.log(data)
setArticle(data.Article)
console.log(data)
})
}, [itemId])
In order to get the image to that article I have to find a FileId by searching the article number against ArticleFileConnections endpoint:
(Documentation)
useEffect(() => {
fetch(`https://api.fortnox.se/3/articlefileconnections/?articlenumber=${itemId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setFileId(data.ArticleFileConnections[0].FileId)
console.log(data.ArticleFileConnections[0].FileId) // Prints an id-number in the console
})
}, [])
When I have the FileId I use it with another endpoint called Archive in order to get the image. Documentation That fetch looks like this:
useEffect(() => {
fetch(`https://api.fortnox.se/3/archive/${fileId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data) // Prints an object thats a folder structure with an empty array
})
}, [])
I tried to change the ${fileid} to the actual id-number in the archive endpoint like this
https://api.fortnox.se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c Then I get this error message in the console:
Uncaught (in promise) SyntaxError: Unexpected token � in JSON at position 0
But I don't get that error if I pass the ${fileid} in the endpoint https://api.fortnox.se/3/archive/${fileid} Although when I console.log the state fileId that I pass in it prints the fileId-number.
So what I expect is that the fileId-state that I use in the archive endpoint should display an image by writing this code.
<div>
<img src={articleImg} alt="product" />
</div>
I hope all this is understandable and I hope someone can help me with what i'm doing wrong.
Thank you.
Note: It all works in postman. When I try the endpoints like the flow above it shows the image with this endpoint https://api.fortnox.se/3/archive/8c05c536-c110-402d-82da-60f25f6b0e1c
Your useEffect for fetching the fileId is behaving as a componentDidMount. What you want instead is a componentDidUpdate behavior, which you can do by
useEffect(() => {
fetch(`https://api.fortnox.se/3/archive/${fileId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'Access-Token': accessToken,
'Client-Secret': clientSecret
}
})
.then((res) => res.json())
.then((data) => {
setArticleImg(data)
console.log(data) // Prints an object thats a folder structure with an empty array
})
}, [fileId]) // Notice the change here. It ensures that the useEffect is called every time the fileId is updated.
I've tried
axios.get(url, {headers:{},data:{}})
But it doesn't work with this.
You should refer to https://github.com/axios/axios#request-config
Check the section for data and header.
As far as I know you can't send body data with GET request. With get you can have only Headers. Just simply change to POST and then you can do something like this :
const bodyParameters = {
key: "value",
};
const config = {
headers: { Authorization: `Bearer ${userToken}` },
};
axios.post("http://localhost:5000/user", bodyParameters, config)
.then((res)=> {
console.log(res)
})
.catch((err) => console.log(err));
};
or if you want to send headers with GET request
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// data is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
https://stackoverflow.com/a/54008789
yeah, it's true it doesn't work to send body in Axios get even if it works in the postman or the backend.
You can try this:
const getData = async () => {
try {
const response = await axios.post(`https://jsonplaceholder.typicode.com/posts`, {
method: 'POST',
body: JSON.stringify({
id: id,
title: 'title is here',
body: 'body is here',
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
}
You can send data in a get request by using the config object and the params option of the config object. This is a workaround and it works, but on the server the data sent is available as request.query not as request.body. Based on the example below you would access your params data on your server using request.query.user_id. It should be noted that using this method will also append the params to your request url which could have unintended consequences based on your specific situation. For example, the url for the request below would be sent as example.com?user_id=1234. You can read more about the axios request config here.
axios.get(
'example.com/',
{
params: { user_id: 1234 },
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
},
);
Unauthorized axios/react response
Hi there friends, I'm trying to connect to an api through Axios and React but an error message appears saying that I don't have access here's my action:
import {SHOW_PROMOTIONS} from './action-types';
import axios from 'axios';
export const showPromo = () => async dispatch =>{
const url= 'https://payment-promotions-dev.travelit.com.ar/api/promotions/packages/';
let config = {
"Content-type": "application/x-www-form-urlencoded",
"Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdW5kaWdlYSIsImp0aSI6ImQ0ODE1ZDk4LTJlYmQtNDRjYS04NGViLTU4N2JjNTY5NzgzZCIsImlhdCI6MTU1NTM0ODUwMCwibm9tYnJlIjoiTXVuZGlnZWEiLCJhcHBsaWNhdGlvbklkIjoiMSIsInBhaXNJZCI6IjEiLCJ0aXBvQXBsaWNhY2lvbklkIjoiMSIsImFjdGl2YSI6IlRydWUiLCJuYmYiOjE1NTUzNDg1MDAsImV4cCI6MTU1NTk1MzMwMCwiaXNzIjoiVHJhdmVsSVQiLCJhdWQiOiJUcmF2ZWxJVCJ9.o4Tv6Cw1Mj5xmHIQQ7abm6k6Ean6s6eQ3IDEkHY6Frk"
};
axios.get('http://<host>:<port>/<path>', url,config)
.then((res) => {
console.log("RESPONSE RECEIVED: ", res);
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
const respuesta = await axios.get(url,config);
dispatch({
type: SHOW_PROMOTIONS,
payload: respuesta.data
})
}
When I execute the component, this error appears: (See following image https://imgur.com/LuKnBv9)
The token is at it's respective header, I don't seem to recognize wat I'm doing wrong.
I even tried to do the request with Postman and it throughs 200: (See image2 https://imgur.com/7UFksPR)
Thanks for the help guys!
You currently aren't actually specifying headers for the request. You would need to add headers property to the config object and put the desired headers into that property. Also, as the comments have you stated, you would also need to specify the type for the Authorization request headers, such as Bearer:
const config = {
headers: {
"Content-type": "application/x-www-form-urlencoded",
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJtdW5kaWdlYSIsImp0aSI6ImQ0ODE1ZDk4LTJlYmQtNDRjYS04NGViLTU4N2JjNTY5NzgzZCIsImlhdCI6MTU1NTM0ODUwMCwibm9tYnJlIjoiTXVuZGlnZWEiLCJhcHBsaWNhdGlvbklkIjoiMSIsInBhaXNJZCI6IjEiLCJ0aXBvQXBsaWNhY2lvbklkIjoiMSIsImFjdGl2YSI6IlRydWUiLCJuYmYiOjE1NTUzNDg1MDAsImV4cCI6MTU1NTk1MzMwMCwiaXNzIjoiVHJhdmVsSVQiLCJhdWQiOiJUcmF2ZWxJVCJ9.o4Tv6Cw1Mj5xmHIQQ7abm6k6Ean6s6eQ3IDEkHY6Frk"
}
};
Hopefully that helps!
I'm new to react and.my problem is that i'm going to make a post request to my node back-end. using react-redux and axios. the thing is my back-end doesn't even hit the request. and no action on the network tab in the browser ether
I have tried lots of another answers but doesn't work
this code is in my redux action page
export const postNominationPayments = function
postNominationPayments(candidatePayments) {
let nominationPayments = {
depositor:candidatePayments.depositor,
depositAmount:candidatePayments.depositAmount,
depositeDate:candidatePayments.depositeDate,
filePath:candidatePayments.filePath,
status:candidatePayments.status,
nominationId:candidatePayments.nominationId
};
return function (dispatch) {
console.log("**",nominationPayments);
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
axios
.post(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
.then(response => {
console.log("))))))))))))",response);
// dispatch({
// type: POST_NOMINATION_PAYMENTS,
// payload: response.data
// })
})
.catch(error => {
console.log("===",error);
// dispatch({ type: AUTH_FAILED });
// dispatch({ type: ERROR, payload: error.data.error.message });
});
};
}
post data is coming as expected.also the back works correctly using postman. but it's not working.
couldn't think of a solution.
what is wrong with my code?
thanks in advance
It should be
axios.post(
`${API_BASE_URL}/nominations/payments`, nominationPayments,
{headers: headers}).
One can drop headers section as well a default is application/json
The way you are passing data to axios post request is incorrect. You need to pass something like below
Change
axios(
`${API_BASE_URL}/nominations/payments`,
{
nominationPayments
},{headers: headers}
)
To
axios.post(
`${API_BASE_URL}/nominations/payments`,
nominationPayments,
{
headers: headers
}
)
axios.get and axios.post takes different kind of arguments and could be hard to remember.
So I usually just stick to the more verbose way:
axios({
method: 'post',
url: `${API_BASE_URL}/nominations/payments`,
data: {
nominationPayments
},
headers
})
.then(response => {
// ...
})
.catch(error => {
// ...
})
Have you checked whether your MongoDB server is up and running?
In my case, my React server was running, however, my MongoDB servers were not. I ran both simultaneously and was able to post data to the back end.