Axios Post request Giving Error 400 , Bad Request - reactjs

I am using the Hackerrank API for a Project.
See the official documentation, click here!
There is an example on their website which uses UNIREST,
unirest.post("https://hackerrank-hackerrank.p.rapidapi.com/https://api.hackerrank.com/checker/submission.json")
.header("X-RapidAPI-Host", "hackerrank-hackerrank.p.rapidapi.com")
.header("X-RapidAPI-Key", "a72a0f1b5dmshdc3f55e233876eap1b8939jsnffad2a5b6e6e")
.header("Content-Type", "application/x-www-form-urlencoded")
.send("callback_url=https://mywebsite.com/responseHandler")
.send("source=puts 'Hello World'")
.send("lang=8")
.send("testcases=["This is input 1", "This is input 2"]")
.send("wait=false")
.send("format=json")
.end(function (result) {
console.log(result.status, result.headers, result.body);
});
Since I am using axios, I converted it to an equivalent axios code which looks like:
var params = {
"callback_url": "https://mywebsite.com/responseHandler",
"source": "puts 'Hello World'",
"lang": 8,
"testcases": "[\"This is input 1\", \"This is input 2\"]",
"wait": false,
"format": "json"
}
var config = {
mode: "no-cors",
headers: {
"X-RapidAPI-Host": "hackerrank-hackerrank.p.rapidapi.com",
"X-RapidAPI-Key": "a72a0f1b5dmshdc3f55e233876eap1b8939jsnffad2a5b6e6e",
'Access-Control-Allow-Origin': '*',
"Content-Type": "application/x-www-form-urlencoded"
}
}
axios.post("https://hackerrank-hackerrank.p.rapidapi.com/https://api.hackerrank.com/checker/submission.json", params, config)
.catch((error) => {
console.log(error.message);
})
.then((response) => {
console.log(response);
})
I expect this to work just the example shown in the example, but it gives me the following error:
Request failed with status code 400
Error: Request failed with status code 400
at createError (createError.js:16)
at settle (settle.js:18)
at XMLHttpRequest.handleLoad (xhr.js:77)
I am relatively new to this, if someone can point out what i am doing wrong, that would be very helpful!

As request Content-Type is application/x-www-form-urlencoded, you should pass data as FromData
var data= new FormData(); // Currently empty
data.append('callback_url', 'https://mywebsite.com/responseHandler');
data.append('source', "puts 'Hello World'");
data.append('lang', '8');
data.append('testcases', "[\"This is input 1\", \"This is input 2\"]");
data.append('wait', false);
data.append('format', "json");
data.append('api_key', "<valid hackerrenk api key>"); // API KEY is mandatory
axios.post("https://hackerrank-hackerrank.p.rapidapi.com/https://api.hackerrank.com/checker/submission.json", data, config)
.catch((error) => {
console.log(error.message);
})
.then((response) => {
console.log(response);
})

Ashish pointed me into the correct direction, but with FormData() I received a status 415 (Unsupported Media Type) instead of the status 400.
What worked for me was using URLSearchParams() instead of FormData(), like in this example:
var data= new URLSearchParams(); // Currently empty
data.append('callback_url', 'https://mywebsite.com/responseHandler');
data.append('source', "puts 'Hello World'");
data.append('lang', '8');
data.append('testcases', "[\"This is input 1\", \"This is input 2\"]");
data.append('wait', false);
data.append('format', "json");
data.append('api_key', "<valid hackerrenk api key>"); // API KEY is mandatory
axios.post("https://hackerrank-hackerrank.p.rapidapi.com/https://api.hackerrank.com/checker/submission.json", data, config)
.catch((error) => {
console.log(error.message);
})
.then((response) => {
console.log(response);
})
(I had a different example with a different URL, but can't share my example since it's an URL from my company)

Related

REACT + Typescript, making API with Axios. headers makes type error

I'm so Newbie in Programming.
I'm using Django as backend, React+Typescript as frontend.
I'm using Axios to make JWT login function. but stuck in the middle.
Because headers/Authorization makes type error.
as above Authorization does not work.
showing this error.
Can anyone help me out of this situation?
Try to remove the null in your condition. Replace it with either undefined or a empty string ""
Authorization: localStorage.getItem("access_token") ? "JWT" + localStorage.getItem("access_token") : ""
const axiosbase = axios.create({
baseURL: 'Your Base URL',
timeout: 5000,
transformRequest: [(data, headers) => {
return data;
}]
});
//default headers
var token = 'Your JWT';
axiosbase.defaults.headers["Authorization"] = 'Bearer ' + token;
axiosbase.defaults.headers["Accept"] = 'application/json, text/plain, */*';
axiosbase.defaults.headers["Content-Type"] = 'application/json';
// Add a request interceptor
axiosbase.interceptors.request.use((config) => {
return config;
}, (error) => {
// Do something with request error
console.log('Error occured while request');
return Promise.reject(error);
});
// Add a response interceptor
axiosbase.interceptors.response.use(
(response) => {
// Do something with response data
//console.log('Response was received');
return response;
},
);
export default axiosbase;

post image to restdb gives Cross-Origin Request Blocked

I'm trying to post an image to restdb media archive, I followed the instructions on their website https://restdb.io/blog/a-picture-is-worth-a-1000-lines-of-code
but all I get is a error
here is my code:
async function fetchPost(url, data) {
let answer
try {
const response = await fetch(url, {
method: 'post', // *GET, POST, PUT, DELETE, etc.
headers: {
'content-type': false,
'x-apikey': '62050e461b941c73ff397a3f',
},
processData: 'false',
body: data,
})
answer = await response.json()
} catch (err) {
console.log(err)
} finally {
return answer
}
}
let formData = new FormData()
formData.append('myFile', e.target.files[0], e.target.files[0].name)
fetchPost('https://mikey-f985.restdb.io/media', formData)
And Here is my API key (CORS)
Just in case you are on the free plan: I had the same issue with GET requests, so i asked restdb directly for help and they answered:
"Yes you can store images for use in development. But to serve them public you need a paid account."

How to send a POST request with variables in React?

I am learning how to send a POST request to an API with React.
What I'm trying to achieve right now is sending a POST request to an API.
The API will insert the event with something like this (what is this method called?):
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
The method that I'm currently using as POST is shown at POST method and it returns me with the error unexpected token '<' in json at position 0 and the result that I get when I console.log(JSON.stringify(event)) is something like this:
{"event_id":"5","desc":"<p>HelloWorld</p>","name":"testing"}```
POST method
const response = await fetch('https://api.com/WebService.asmx/insertEvent',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(event)
})
Edit: I've fixed the above error by encoding the HTML that I need to send. This is now my latest POST method, but I'm still facing error 500 for some reason even though it works when I copy and pasted the URL+params from the console.log that has the error shown:
const addBulletin = async (event) => {
console.log(event, '--event')
const url = 'https://api.com/WebService.asmx/insertEvent';
axios.post(url, null, { params: {
title: event.title,
desc: event.desc,
image: event.image,
employee: event.employee,
entity: event.entity,
startDate: event.startDate,
endDate: event.endDate,
createdBy: event.createdBy
}})
.then(response => console.log(response.status))
.catch(err => console.warn(err));
};
Edit: I've tested the API on a vanilla JS project using .ajax with POST, and it works, so I think the API shouldn't be a problem.
var json = $('.insert-form').serialize();
$.ajax({
type: "POST",
url: "https://api.com/WebService.asmx/insertEvent",
data: json,
async: true,
success: function (response) {
alert("Event has been successfully created!");
},
error: function (response) {
console.log(response);
}
});
The API you are sending the request to expects a query parameter (data in the URL).
https://api.com/WebService.asmx/insertEvent?event_id=5&desc=<p>HelloWorld</p>&name=testing
In this request, we are sending 3 query params: event_id, desc, and name.
To send this kind of request from React, you should not use request body. Instead. I advise you to use axios to make it easier. It's a very powerful library, better than using fetch. It should be done this way:
axios.post(`https://api.com/WebService.asmx/insertEvent`, null, { params: {
event_id: eventId,
desc
}})
.then(response => response.status)
.catch(err => console.warn(err));
This may help: How to post query parameters with Axios?

POST request with axios ReactJS

I'm new to HTTP requests and trying to do POST request of my form submitting with axios and getting an error 400. I want to send my data to url and it should be seen there in JSON format.
codesandbox https://codesandbox.io/s/fast-brook-g3488?file=/src/App.js
Error is very clear you are not passing data to axios post method.I am not sure what kind of validation you have in server but it will be look like this
axios({
method: "post",
url: "https://frosty-wood-6558.getsandbox.com:443/dishes",
headers: { "Content-Type": "application/json" },
data:{
name:event.name,
preparation_time:event.preparation_time,
type:event.type,
spiciness_scale:event.spiciness_scale,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
Since its now throwing error preparation time validation. Not sure what's the validation you have in server side
preparation_time: "Wrong format"

ReactJS catch HTTP error

I have the next problem: I made authentication using Spring Security and after entering incorrect data, it(java server) sends HTTP 401 status code.Image
I can't catch this exception. I'm using fetch API, but catch doesn't work and response.status too. How can I solve this?
login = (event) => {
event.preventDefault();
var data = {username: this.refs.username.value, password: this.refs.password.value};
var that = this;
fetch('http://localhost:8080/login',{
method: 'POST',
mode: "no-cors",
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
}).then( (response) => {
console.log(response);
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
} else {
console.log('Yeeee man, you can login');
this.props.history.push('/');
}
}).catch(error => console.log('Error ' + error));
}
Check the object first console.log(response.status) or try use response.data.status
Sometimes the response is placed inside the object data
I found the solution. The problem was in mode: 'no-cors'. It means that I can send the request but I will not be able to read the response... So I needed to enable cors in java.

Resources