Rest API and Axios Request - javascript

I've written this code:
doIt(evt) {
axios.get('/book', {
params: {
id: 1
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
I want to get the book with id = 1
I'm using a server running in nginx.
I don't know how to receive this request in the server and how to send the response to my client.
Help me please.

When you have a JavaScript front end that consumes a REST API back end, you have programming logic at both ends.
On its own, nginx is typically used for server static files or reverse proxying - it doesn't have its own way of serving a REST API.
You would typically use a web framework with a database to do the back end logic of serving the API. One example of this is Django with Django REST framework.
Here is an example of how you might set up such a back end stack. Many other web frameworks are available that can be set up with nginx and do a similar job.

Related

How to consume Notion API with React

I'm trying to use the new Notion API as a CMS for my personnal website.
As a way to improve, i tried to use it with React. But it seems that it does not allow CORS (i use Axios).
What is the best way to consume this API ? Use an Express.JS Back-end ? I would think it's overkill for my use (I just want to read pages & blocks, not edit).
Here is my actual API Call, but from React :
const getPages = (apiCmsPage) => {
var config = {
method: 'get',
url: 'https://api.notion.com/v1/blocks/'+ apiCmsPage +'/children?page_size=100',
headers: {
'Authorization': KEY,
'User-Agent' : 'PostmanRuntime/7.26.8'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
In fact, I never really experienced back-end, so I don't know if it's really obligated to use the API.
Thanks.
I solved this problem by Next.js.
I tried the official notion-sdk-js, but still can’t solve this problem, because it may be aimed at the server instead of the client.
By using the getServerSideProps of Next.js, Notion data can be obtained through fetch before each client request, and then the rendered page is directly returned to the client. Because the request is completed on the server side, there is no CORS problem. But the price is that you have to keep a Next.js process in the background for rendering the page.
Would you consider using a react framework like NextJS? You can use its SSG feature to generate the pages during build time, in which your credentials will not be visible on client side.
https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
Notion also has an official js sdk, so you don't have to do all the API call hard work:
https://github.com/makenotion/notion-sdk-js

Is it bad practice if I use one endpoint to monitor another endpoint?

I have a web application with various endpoints, and I have to create a dashboard tool to monitor the statuses of those endpoints.
For example, one of my web application endpoint is base-uri/api/v1/apple/.
On my dashboard, I need to display whether the server status is up/down at that endpoint. I'm currently writing the backend of my dashboard using Node and Express, and a snippet of it looks like this:
app.get('/testAppleEndPoint', function (req, res) {
fetch('base-uri/api/v1/apple/')
.then(response => response.json())
.catch(error);
})
When I go to my dashboard endpoint /testAppleEndPoint, it will use fetch to test whether my web application's end point base-uri/api/v1/apple/ is working or not.
Is this bad practice?

How would I create an android app with an array stored on a web server using android studio?

I am trying to make a 'shower thoughts' app. It has three categories stored in arrays. Underneath each are nested the actual list of user posts that the user can see (as arrays) . Of course, a user wont be able to see others posts. I have a rasbpi I am using as a webserver. The way I thought of doing this is a bit of javascript code on the web server that contain two functions: One that adds a users post to an array (with the input arguements being the post itself) and one that returns the array so that the app can update. However, I have no idea how to CALL this js file on the web server from the application. How would I do this?
You will have to construct a web API for this. You can do this using NodeJS on the server and then send requests to this API in Android
Basically what you are trying to do is create a simple Server-Client Architecture.
There are multiple ways to do so. I am going to explain using NodeJS as the server and volley on the client (android) side.
Firstly you can use Volley, to create an API call from android, that would interact with the NodeJS API, which in turn will create the array and store it in either SQL or any other form you want.
For reference you can check out this two projects.
This is an Android app which is using Volley to communicate with the server.
This is the NodeJS Server which is a simple REST API.
You can also use this link to learn basics about NodeJS if you don't know.
This is the basic NodeJS code to create a server and then send a response to the client.
var http = require('http');
//create a server object:
http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
This is the basic Android Volley code to make a request to the server.
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText("Response is: "+ response.substring(0,5));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
If you don't understand any of these code you can comment below.

Getting data from a API on the client side without giving the key

Currently I am making a page that display's data gathered from an API. Most of the data is updated on the server side every 4 hours but some of it is updated whenever a client requests the index route. As a result, there is a delay in the index file being sent since the data needs to be updated. I want to gather the updated data after the page has been requested and sent so there is no delay. My first idea was to make the request on the client side which will handle updating the display after the data is gathered but from my knowledge, I don't know how to do that without giving them the API key. Should I approach the problem this way or is there a better way to do it? I'm using Express for the back-end, Axios is used to make the get requests, and EJS is the template engine.
Here is the code:
// This is called before the data is send in a for loop
data.gameData[i].player_count = await SteamModule.liveGetCurrentPlayers(data.gameData[i].appid);
res.render('index', {data: data});
// This is the function that is called
liveGetCurrentPlayers: async (id) => {
const res = await axios.get(`${base}/ISteamUserStats/GetNumberOfCurrentPlayers/v1/?key=${key}&appid=${id}`, {timeout: 1000}).catch(err => {
Logger.error("Error getting updated user data per request");
return 'Error';
});
if(res.data) {
return res.data.response.player_count;
} else {
return 'Error';
}
}
Here's a bit of a drawing to explain what I've said in comments.....
(the code you showed should constantly update - without other info I can't help with whatever the other issue was, but this is the overall idea....)
Where:
Client requests data from you (your server)
Your server sends html and css to show a 'frame' of the page (no data, just something for them to see and feel like something is happening...)
Your server requests data from the API server (all the various "20-ish" things you said you wanted to serve....)
As the data is updated (or you may have it already), you send the data to the client, updating their 'frame' page with current data.
You can maintain your keys on the server side and add restriction that those API's can only be accessed by your client side URL. So you would access the API and it will maintain your session and handle the authorized KEY part as well.
Anything and everything on the client side is accessible if it running in your browser.
You can add security measures on the server but not on client side for protecting your key.

How to use node.js as gate to a website

I got an old website on a webserver. It is to big and not structured well enough but needs to be improved by e.g. Account management. As it is (in my opinion) at its end of lifetime, we do not want to put more effort in it but instead migrate to new technology. For that, we want to use node.js and AngularJS, because the whole project is more a webapp than it was at the beginning. As a migration concept, we want to include the old stuff via a kind of routing through the node.js server and replace it step by step. For that I looked into the "request" library without getting the right grip.
Goal is, to route some requests after authorization check to the old server, without leaving the new server (gate). For that I need to check and parse the gets and posts. Some other requests have to response by the node.js server itself.
As I think that I am not the only one with that approach I am asking for experience in that matter.
I had to do something similar, because we made a new API which was not compatible with the first version and some features were not implemented in the newer API so we had to do like a bridge. Authentication was happening in the first server, and then we were routing the request to the old API and then returning to the user.
The approach I took was using a module like request to make the call in the old server.
Assuming you are using expres for your new API, you can do something similar
var request = require('request');
app.get('/test', function(req, res) {
//authenticate stuff
var options = {
url: 'http://oldendpoint.com/test',
headers: {
//headers for authenticate in the old endpoint
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(body); //this will send it back to your client
}
});
});
Basically you get a request to your new API (node.js app) in the /test endpoint and this, after auth or after whatever check, will forward the request to the old system, and then it will return some data which is forwarded to the client who made the request in the first place.

Categories

Resources