Requesting with Axios to fetch data from API
export const getReports = async (url, obj) => {
return new Promise(
async (resolve, reject) => {
try {
const data = await axios.request(
{
method: 'get',
url: BASE_URL+url,
headers: {
'Authorization': `Bearer ${await getAccessToken()}`
},
data: {date_to:'2019-11-05',date_from:'2019-11-05',c_name:'1'}
}
);
resolve(data);
} catch (e) {
reject(e)
}
}
)
};
Getting error and not able to receive request.data on the backend...
Working on Postman
in Body
- date_to:'2019-11-05'
-date_from:'2019-11-05'
-c_name:'1'
If you have request type of GET axios doesn't use the data field.
(From the docs)
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be of one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream, Buffer
data: {
firstName: 'Fred'
},
The data field is for POST, PUT, PATCH, etc. You could try using query params or change the type of the request.
Here is about query params from the docs
// `params` are the URL parameters to be sent with the request
// Must be a plain object or a URLSearchParams object
params: {
ID: 12345
}
So this would appear as url.com?ID=12345
Then you can parse them from the backend. This is also the HTTP standard and you shouldn't try sending body data with GET request.
Related
When trying to get a dummy response from a POST endpoint, the call to res.json() throws a serialization error in the client:
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This is the client side:
const body = /* request body */
const res = await fetch(/* url */, {
method: 'POST',
body: JSON.stringify(body),
})
console.log(await res.json())
And this is the endpoint:
export const POST = async ({request}) => {
/* do something with the request's body */
return {
body: {a: 1}
}
}
I get the same error on the server side if I don't stringify the body in fetch, but I can't stringify it in the endpoint, as only plain objets (and errors) are allowed.
The outcome is the same with an empty object.
You have to instruct the endpoint to send JSON, otherwise it will send the associated page as server-side rendered HTML. To do that add an Accept header:
const res = await fetch(/* url */, {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: JSON.stringify(body),
})
I have created a config file to create an Axios.
export const http = axios.create({
baseURL: process.env.REACT_APP_API_URI,
responseType: "json",
timeout: 30000,
timeoutErrorMessage: "Request Time out",
headers: {
withCredentials:true
}
})
In the other file, I have created helper functions to post, update, and get. Now I am trying to pass data from the body through the get function so far I have following code to get data without passing the body.
export const getRequest = (url, is_strict = false) => {
return new Promise((resolve, reject) => {
http.get(url, {
headers: getHeaders(is_strict)
}).then((response) => {
if(response.status === StatusCodes.OK || response.status === StatusCodes.CREATED){
resolve(response.data);
} else {
reject(response);
}
})
.catch((error) => {
reject(error);
})
})
}
How can I achieve that?
You cannot have a request body in GET method. You can use request params instead. Or you can use POST method.
Form the MDN docs for GET,
property
avaiability
Request has body
No
Request has body
Yes
Quick question: I made a API fetch function for my Strapi CMS but can't seem to get the right JSON.
This results in my API call adding a new item within the Strapi CMS (200 OK HTTP). But without the provided data. I'm guessing that the JSON is wrongly formatted and the data gets lost.
What works:
Authorization works
API request works (200)
There is an empty article within the Strapi CMS
What doesn't work:
Data doesn't get set within the CMS.
The code:
// POST request using fetch with error handling
function setArticle() {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state.jwt}`
},
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})
};
fetch('http://localhost:1337/articles', requestOptions)
.then(async response => {
const data = await response.json();
console.log(requestOptions);
// check for error response
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
return Promise.reject(error);
}
this.setState({ postId: data.id })
})
.catch(error => {
console.error('There was an error!');
});
}
What I tried, logging and reading the Strapi documentation.
The problem was, case sensitivity. Apparently when making a new content type within Strapi I set the entity with an uppercase. (Slug and Name) resulting to my body within my HTTP request getting ignore.
I changed the Strapi fields without an uppercase and it's now working.
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})
I currently work with an api rest where I pass the controller parameters, version and action via URI. However, when I execute a request with URI with more than 19 characters, it gives this CORS error:
Access to XMLHttpRequest at 'http://my-api-host/toll/vehicle/v1/list' from origin 'http://localhost: 3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
In authentication the request works even with URI having more than 19 characters. However, any other request with a different URI that has more than 19 characters gives this same error. I use my application's API and the request works normally.
I'm using axios in Reactjs.
The api is already configuring to accept the content-type I am using (application / json) and is also already accepting requests from different sources.
My request code:
request(uri, params = {}){
return new Promise((resolve, reject) => {
axios
.post('http://my-api-host' + uri, JSON.stringify(params), {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.data.success) {
resolve(response.data);
} else {
reject(response.data);
}
});
});
};
Has anyone been through this and could help? thanks in advance
Did you use Fetch instead?
async function postData(url = '', params = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
headers: {
'Content-Type': 'application/json'
},
qs: JSON.stringify(params) // query string data
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('http://my-api-host', params)
.then(data => {
console.log(data);
});
I am new to ASP.NET Core and React js.
I am not able to get the response in React from the ASP.NET controller endpoint. All code at the backend is executing from start to return response line and getting data at the return line but in the response of react js, I am not able to see the data.
I tried :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.InputFormatters.Add(new BypassFormDataInputFormatter());
options.RespectBrowserAcceptHeader = true;
options.InputFormatters.Add(new BypassFormDataInputFormatter());
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
}).AddXmlSerializerFormatters().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
this is my front end :
getRecordsByPaging = (pagingData) => {
debugger
var jsonData = JSON.stringify(pagingData);
return fetch('/get-products', {
method: 'POST',
body: jsonData,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
return res;
}).catch(err => err);
}
this is my backend:
[HttpPost]
[Route("get-products")]
public async Task<IActionResult> GetCustomers([FromBody] req)
{
try
{
if (!ModelState.IsValid)
{
return null;
}
var response = await _productSvc.GetProducts(req);
if (response == null)
{
return null;
}
return Ok(response);
}
catch (Exception e)
{
return null;
}
}
I do not know what am doing wrong .
I am getting at react js side :
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "https://localhost:44384/get-products"
__proto__: Response
You need to read the actual response of your ajax request:
getRecordsByPaging = (pagingData) => {
var jsonData = JSON.stringify(pagingData);
return fetch('/get-products', {
method: 'POST',
body: jsonData,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(r => r.json())
.then(res => {
return res;
}).catch(err => err);
}
As you can see, the added line is .then(r => r.json()) which will actually get the JSON response from your request.
You can read more about the fetch api at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Basic fetch:
A basic fetch request is really simple to set up. Have a look at the
following code:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
Here we are fetching a JSON file across the network and print it to
the console. The simplest use of fetch() takes one argument — the path
to the resource you want to fetch — and returns a promise containing
the response (a Response object).
This is just an HTTP response of course, not the actual JSON. To
extract the JSON body content from the response, we use the json()
method (defined on the Body mixin, which is implemented by both the
Request and Response objects.)