Axios POST request - reactjs

I am trying to send some data from a form to a database using Axios. Here is the code:
const handleSubmit = async () => {
try {
const response = await axios.post(
ApiUrl,
{
batchId,
name,
description,
source,
},
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
console.log(response.data);
handleModal();
} catch (error) {
console.error(error.response.data);
}
};
The error I get is this:
AxiosError {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …}
The values are being stored with useState. The database is receiving inputs but with no data.
I was investigating and I think I need to convert the JSON data to string, but I am not sure how to do that for my code.

If the database is receiving inputs but with no data, it sounds like the API endpoint is being hit properly but you are either improperly extracting the data from (Express?) or improperly passing the extracted values through to whatever function stores them in the database.
You do not need to stringify your axios.post payload.
If you're using Express, make sure you're properly extracting the data from req.body in your endpoint handler. If you're using req.params or req.query that would be a problem.
I would set up some console.log('###') markers in your backend code to ensure the data is reaching the query insertion point.
If you are still having issues, please provide more context regarding your backend logic and the trail between your API and the Database.
I hope this helps!

Related

Django server unable to get data from react Axios

I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue!
My react axios request
// PrivateAxios instance to send api request
const axiosPrivate = useAxiosPrivate();
const handleSearch = async () => {
const data = JSON.stringify({ from_company: keyWord });
try {
const response = await axiosPrivate.get(SEARCH_URL, data);
console.log(response);
setRecords(response?.data);
} catch (err) {
if (!err?.response) {
console.log("NO SERVER RESPONSE");
} else {
console.log("SOMETHING WRONG");
}
}
};
Server log
{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276
The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app.
Request sent from Postman returns
{'from_company': 'Jethmal Paliwal'} <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284
I have double checked everything, my headers are set correctly, Content-Type: application/json, withCredentials: true, and every other possible settings, Even every request from other components works great, but why this particular request doesn't reach the server?
Tried writing the data as an Object in the request funcion itself
const response = axiosPrivate.get(SEARCH_URL, { "from_company": "Jethmal Paliwal" }); which doesn't work as well. The same empty object gets printed.
Tried JSON.stringify the data, which doesn't work as well.
I believe that axios is omitting the data as it's not per REST standard to submit data in the GET request. HTTP allows that, but people and apparently libraries are not expecting it.
This is the API for axios get method:
axios.get(url[, config])
as you see there is no data in the method signature. And if we look at the POST method:
axios.post(url[, data[, config]])
I suggest if you have data to submit to server that you use a POST method instead.

Getting 400 Bad Request error when sending form data Angular

I am getting a 400 Error when sending a form data to my node.js backend. It also gives me this error: Unexpected token - in JSON at position 0 I know that it isn't a problem with my node app because I can send the same data using Postman and it works perfectly.
This is my Angular method:
const formData = new FormData();
formData.append("db", $scope.item.db.toLowerCase());
formData.append(
"collection",
$("#collection")
.find("option:selected")
.text()
.toLowerCase()
);
formData.append("owner", JSON.parse(sessionStorage.getItem("user"))._id);
formData.append("name", $scope.item.name);
formData.append("description", $scope.item.description);
formData.append("year", $scope.item.year);
formData.append("photo", $("#picture")[0].files[0]);
$http.post("items/uploadItem", formData).then(function(response) {
console.log(response.data);
});
};
If you need any more information, please leave a comment and I would be happy to provide it.
The Angular $http service is expecting standard objects, not a form object. You are sending a serialised form object to your end point. Try
const formData = {
db: $scope.item.db.toLowerCase(),
// and the rest of your object properties.
};
It turns out that I was still sending the data as a json doc. The trick was to change the http call to this:
$http.post("items/uploadItem", formData, {headers: { "Content-Type": undefined }})

How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.
This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:
curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool
This is the React state hook for setting the data to the fetched data:
const [jiraTicket, setJiraTicket] = useState([]);
This is the fetch function for the API request (${} will be filled with user input):
function getJiraTicket() {
axios.get(`${username}:${apiToken}#Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
.then((res) => {
const data = res.data;
setJiraTicket(data);
})
}
The button inside the react component return should invoke the fetch function:
return(
<Container>
<Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
</Container>
);
This is the error I'm currently getting, because the authorization is not working the way I did it
(I replaced the provided username, API token etc. for this example):
GET http://localhost:3000/username:apitoken#https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)
Edit:
My current approach:
function getJiraTicket() {
axios.get(`${userName}:${apiToken}#https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
auth: {
username: userName,
password: apiToken,
},
withCredentials: true
})
.then((res) => {
const data = res.data;
console.log(data);
setJiraTicket(data);
})
.catch(err => {
// This error means: The request was made and the server responded with a status code
if(err.res) {
console.log(err.res.data);
console.log(err.res.status);
console.log(err.res.headers);
console.log("request was made and server responded with status");
// The request was made but no response was received
} else if (err.request) {
console.log(err.request);
console.log("request was made, but no response was received");
// Something happened in setting up the request that triggered an error
} else {
console.log("Error", err.message);
console.log("request is note set up correctly");
}
console.log(err.config);
})
Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"
Endpoint that works well in Postman (Basic auth is provided in Postman):
https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid
Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:
https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent
Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues
Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:
let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
baseURL: axiosUrl,
method: 'get',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin", "*"
},
//timeout: 2000,
auth: {
username: userName,
password: apiToken,
}
})
.then((res) => {
setJiraTicket(res.data);
})
.catch(function (error) {
console.log(error);
});

send file from formik reactjs to springboot using axios with saga

i can send file "userPicture" from postman and get it in the backend (springboot )and i save it to my database mongodb without any problem
but when i send the picture from the form i use Formik component in reactjs and axios
i display the content of my input userPicture i get
in axios i made this to sent the request. for boundary i dont know what is i made copy past "WebKitFormBoundaryQ0pBuvRC1EzDAQWT" from an exemple
try {
const { user } = action;
console.log(user);
const request = yield axios({
method: 'post',
url: ENDPOINTS.USER + '/add',
data: user,
headers: { 'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundaryQ0pBuvRC1EzDAQWT----' }
});
in the backend i get this error
,org.springframework.validation.BindingResult,org.springframework.web.multipart.MultipartFile,org.springframework.web.multipart.MultipartFile)
throws java.io.IOException: Required request part
'userPicture' is not present
i get the same error in postman when i send request without userPicture parameter
Looks like you sending the file incorrectly. If you want to send multipart/form-data from client to server, you need to use FormData.
Like this
const formData = new FormData();
formData.append('usePicture', user)

Fetch GET request hitting .catch() on anything but 200 response

I have a redux store set up with actions to handle loading accounts. The action calls a service like so:
const requestOptions = {
method: 'GET',
headers: authHeader()
};
return fetch(`http://localapi.co.uk/api/account/load/${account_id}`, requestOptions)
.then(handleResponse)
.then(account => {
if(account.account.id) {
localStorage.setItem('account', JSON.stringify(account))
}
return account;
})
.catch(redirectToLogin)
Handle response is simply a function that checks the .status and .ok properties of the response and either displays an error or logs out if the response status is 401. This works perfectly fine for POST requests. When I hit my login route, any response hits the first .then(handleResponse) and deals with it.
When I send a GET request instead like above 404s, 401s, 500s.. etc all skip the .then(handleResponse) and instead jump to my catch. The problem that causes is that because catch doesn't actually give me a response object to work with I can't check the status - I want to do different things depending on whether the get was a 401 (I want to logout) or a 500 (I want to display a user error stating what went wrong) for example.
Is there a solution that will allow me to get a response or stop my GET requests hitting the .catch and instead hit the response handler I've written?
I'm using:
a Laravel 5.7.20 back-end
a React 16.7.0 front-end
running local node server with npm start
How about having a clean async/await function. Waiting till you JSON data becomes ready and then having the rest of your if logic or returning the account object from the function and moving the rest of the logic to the caller function. Something like this:
async myFunc({ account_id}) {
const url = `http://localapi.co.uk/api/account/load/${account_id}`;
const response = await fetch(url, { headers: headers: authHeader() });
const account = await response.json();
// return account (recommended);
// Place your if logic here (not recommended because its not clean)
}

Resources