React JS (Admin on Rest) error when API call - javascript

I'm making a API call (GET) using React js (Admin on Rest).
I already check on API server when I call to localhost:5001/cites, server return cities data, but I don't know it error on client side, here is log from browser :
failure.js:18 Error: The X-Total-Count header is missing in the HTTP Response. This header is necessary for pagination. If you are using CORS, did you declare X-Total-Count in the Access-Control-Allow-Headers header?
at convertHTTPResponseToREST (http://localhost:3000/static/js/bundle.js:33928:28)
at http://localhost:3000/static/js/bundle.js:33966:21
and
failure.js:18 Error: The Content-Range header is missing in the HTTP Response. This header is necessary for pagination. If you are using CORS, did you declare Content-Range in the Access-Control-Allow-Headers header?
at convertHTTPResponseToREST (http://localhost:3000/static/js/bundle.js:33010:28)
at http://localhost:3000/static/js/bundle.js:33037:21
May someone can help ? Thanks

Admin-on-rest needs a way to determine how many results there are in total, even if your API returns only a subset of the results - in order to build the pagination controllers. For instance, if the API returns 10 results but mentions there are 100 results in total, admin-on-rest will display 10 page links.
The simpleRestClient and jsonServerRestClient both expect to see this information in the response headers, either in X-Total-Count, or in Content-Range.
If your API doesn't include these headers, you can:
update your API to include the total as X-Total-Count header, or
write your own RESt client to grab the information about the total number of records somewhere else (e.g. in the response body)

Update your backend API function to get X-Total-Count and set it to Response Header
Example:
exports.findAll = (req, res) => {
var total = Data.countAll()// your count all function
Data.findAll({ where: condition })
.then(data => {
res.set('Access-Control-Expose-Headers', 'X-Total-Count')
res.set('X-Total-Count', total)
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving data."
});
});
};

Related

Unable to retrieve data from axios GET request

I've been trying to send a GET request to an api to fetch data using Axios but always get a response object with status, headers, config, agents etc and response.data is always empty.
For example, the following code returns me an Axios response object with the hasBody set to true and data being empty.
axios.get(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings/`).then(response => {console.log(response);
console.log(response.data);});
However, when I switched over to using Request library which has been deprecated, I am able to get the response body. For example, the following code works:
request(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings/`, { json: true }, (err, res, body) => {
if (err) { return console.log(err); }
console.log(body);
});
Can someone tell me what am I doing wrong and how can I get the response body using axios? I'm a beginner and have spent hours trying to figure out so I would really appreciate any form of help.
It's not an axios library issue. From what I can tell, the server does't like the user-agents starting with "axios/". Specifying some user agent gives you the expected result:
const axios = require("axios");
axios.get(`https://fantasy.premierleague.com/api/leagues-classic/12000/standings`, {
headers: {
'user-agent': 'not axios',
}
}).then(response => {
console.log(response.data);
});
As for why the requests library works but axios does not: axios is setting the user-agent header to something like axios/0.21.1 or whatever version you have. requests on the other side, leaves the user-agent header unset. It's the server right to handle the request as he pleases.
I have verified the response from this URL https://fantasy.premierleague.com/api/leagues-classic/12000/standings/ - there is no data property in the response
Try like below to read the values:
It seem like your URL at https://fantasy.premierleague.com/api/leagues-classic/12000/standings/ had invalid response body.

Process multiple unique Express JS requests

I've got a small Express JS api that I'm building to handle and process multiple incoming requests from the browser and am having some trouble figuring out the best approach to handle them.
The use case is that there's a form, with potentially up-to 30 or so people submitting form data to the Express JS api at any given time, the API then POSTS this data of to some place using axios, and each one needs to return a response back to the browser of the person that submitted the data, my endpoint so far is:
app.post('/api/process', (req, res) => {
if (!req.body) {
res.status(400).send({ code: 400, success: false, message: "No data was submitted" })
return
}
const application = req.body.Application
axios.post('https://example.com/api/endpoint', application)
.then(response => {
res.status(200).send({ code: 200, success: true, message: response })
})
.catch(error => {
res.status(200).send({ code: 200, success: false, message: error })
});
})
If John and James submit form data from different browsers to my Express JS api, which is forwarded to another api, I need the respective responses to go back to the respective browsers...
Let's make clear for you, A response of a request will only send to the requester, But if you need to send a process request and send a response like, hey i received your request and you can use another get route to get the result sometimes later, then you need to determine which job you mean. So You can generate a UUID when server receives a process request and send it back to the sender as response, Hey i received your process request, you can check the result of process sometimes later and this UUID is your reference code. Then you need to pass the UUID code as GETparam or query param and server send you the correct result.
This is the usual way when you are usinf WebSockettoo. send a process req to server and server sends back a reference UUID code, sometime later server sends the process result to websocket of requester and says Hey this is the result of that process with that UUID reference code.
I hope i said clear enough.

How to get all reviews in themoviedb api?

I am creating a rest api , I would like to retrieve or get all reviews/comments which are in a database.
This is what I have done :
app.get('/review', (req, res) =>{
request('https://api.themoviedb.org/3/review?api_key=4d9c9de3bdf0d3b6837c49c086e3b190', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred and handle it
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.send(body)
});
});
I am getting this error:
{"status_code":34,"status_message":"The resource you requested could not be found."}
what am I doing wrong here? help
Note: other methods works perfectly
This isn't a JS error or anything. If you look at the API Documentation, status_code: 34 means you're accessing an endpoint that doesn't exist.
Diving into the docs a bit further, you can't get ALL the reviews in the database. All you can do is get the reviews on a per movie basis. Try this URL:
https://api.themoviedb.org/3/movie/401478/reviews?api_key=4d9c9de3bdf0d3b6837c49c086e3b190
Here's the documentation on the /movie/<movie_id>/reviews endpoint: https://developers.themoviedb.org/3/movies/get-movie-reviews
There is also the /review/<review_id> end point, but it appears that gets a single review by id which probably isn't what you're looking for:
https://developers.themoviedb.org/3/reviews/get-review-details
It has nothing to do with nodeJS.As stated by #VicJordan, the problem is only with the url you are trying to search, it's simply not a valid API request. Try to go thru API documentation to find out how to use them. An example of a valid URL would be:
https://api.themoviedb.org/3/discover/movie?api_key=4d9c9de3bdf0d3b6837c49c086e3b190

Why am I not getting a JSON object in the response from my local node.js/express server?

-- The background to situation --
I'm making an e-form signup for a client of our business marketing strategy service blah blah blah...
the form is done and looks great. now I need to hook it up to the existing API of the service our business uses to hold/sort/query/etc the submitted information.
I'm a very junior developer and the API is very complex. I just want to make sure my ES6/javascript is in proper working order. The ajax calls are working, no bugs in my code etc. So it seemed the quickest easiest thing to do in order to test things was just make a simple local server so I can test my calls get everything working BEFORE I start going through tons of API documentation and getting it properly hooked up to our service. The first call seems to work fine. But I couldn't get my lil' baby server to "respond" properly with some static info to parse through. I'm primarily a front-end developer, but I'm obsessed with figuring this little server problem out at this point... So help would be VERY appreciated.
-- the fetch request --
fetch('http://localhost:4000/send-zip')
.then(
(response) => {
response.json(),
console.log('begin fetch to local server'),
console.log(response),
populate_store_selector(response)
})
.catch(
(error)=> console.log('basic fetch request failed' + error)
)
-- that other function in case people ask --
(it is simply meant to iterate through and populate an html
input type="select" )
function populate_store_selector(arg) {
for (i of arg) {
let new_option = document.createElement('option')
new_option.innerHTML = arg[i]
select_shop.appendChild(new_option)
}
}
-- my little baby server --
const express = require('express')
const server = express()
server.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
server.get('/send-zip', function (req, res) {
res.send({ "options": ['option1', 'option2', 'option3'] })
})
server.listen(4000, () => console.log('mock server listening on port 4000!'))
the server works just fine and does it's job OTHER than I'm never able to get it to send a JSON object back :(
I've tried lots of things so far. Honestly it doesn't matter as my request on the front end works just fine but I'm too obsessed to let this go right now...
-- what the console.log() shows in the browser --
begin fetch to local server
main.js:104
Response {type: "cors", url: "http://localhost:4000/send-zip", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: trueheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "cors"url: "http://localhost:4000/send-zip"__proto__: Response
main.js:108
basic fetch request failedTypeError: arg is not iterable
You might try parsing the response after the response stream completes, and then taking action on the data.
fetch('http://localhost:4000/send-zip')
.then(
(response) => {
return response.json();
}).then(
(response_json) => {
console.log('begin fetch to local server'),
console.log(response_json),
populate_store_selector(response_json)
})
.catch(
(error)=> console.log('basic fetch request failed' + error)
)
The reason that you need to include the additional .then step and return response.json() is that the http response object returns the body data as a readable stream.
The JSON function is designed to accept a stream and convert it into JSON after the stream completes. This may feel somewhat unintuitive for anyone familiar with axios or other AJAX convenience libraries, as that part of the process is abstracted from view.
What this basically means is that after you wait for the response http object to be returned, you need to wait again for the stream to also complete.
There are a few different methods available which can act upon a stream upon completion including arrayBuffer,blob, and text (there are a few more I think as well). Usually they tend to convert the data into the format you prefer after it has completed.

Ionic 2 : Get the header of a response in http request

I want to have some information about the response when I request an API with http in Ionic 2 / Angular 2.
Informations like : response time, response size ... ect.
I use this code :
let url : "[myUrl]";
this.http.get(url).map(res => res.json()).subscribe(res => {
console.log(res);
});
I want to get the response header.
Someone know how to do that ? :)
this.http.get(url).map(res => {
console.log(res.headers); // Print http header
return res.json();
}).subscribe(res => {
console.log(res);
});
Angular Http request returns an Observable which contains all the information the server has passed. So you can access headers from the response as res.headers. To obtain the size of the response body you can use,
res.headers.get('Content-Length')
assuming this is present in the headers. So it depends on the information the response carries rather not what angular provides.
Response time information depends on what exactly you are looking for. For server response time in node.js you can use this package. Then in response , response time can be obtained with
res.headers.get('X-Response-Time')
If you want the total response time (including the network delay ) you will have use JavaScript timer and find the time difference between request and response.
So the information you are looking for mainly relies on the server response rather than angular. And beware of CORS in browser ( Access-Control-Expose-Headers in response header ) . You can understand more about headers here. Hope it helps.
You can. In the map function you can get the all the information regarding HTTP call. You can do whatever you want with the result (I've added only a console.log)
this.http.get(url).map(res => {
console.log(res); // Print http details
return res.json();
}).subscribe(res => {
console.log(res);
});

Categories