How to use my node API calls in my react? - node.js

I'm new to react and I have some comprehension issue. On my project I have the backend made in node. Node is use to make the api's call. But my issue is that how Am I suppose to get the data from the json returned by the node in my react ? I tried to store the function inside a variable, but I have an error saying that it's an object and not a function so toto can't hold it.
Here's the example.
Nodejs
module.exports.getArtistTopTracks = async (id, market = "from_token") => {
if (!global.userInfo && !global.userInfo.access_token)
return undefined;
const result = await fetch(`https://api.spotify.com/v1/artists/${ id }/top-tracks?market=${ market }`, {
method: "GET",
headers: { "Authorization": `Bearer ${ global.userInfo.access_token }` }
});
return await result.json();
};
and in my react I tried to stock it like that
import { 'getArtistTopTracks' } from 'my_path'
function tata()
{
var toto = getArtistTopTracks()
console.log(toto)
return (
<div>
<PrimarySearchAppBar />
<h1 style={{fontSize: 50}}>Discover</h1>
</div>
)
}

React is a frontend library. With the exception of server-side rendering (which I'll talk about below), it is supposed to run on the client-side (the browser), not on Node.JS. You will need to find a way of communication between your Node.JS backend and your React frontend. The usual way is to issue HTTP requests from your frontend and handle them on your backend.
One exception to this is using server-side rendering where the React library is used to create HTML (as a string) so that the page loads instantly, at which point the client-side React takes over to process events and such. But even then, since the same React code is gonna run on the client as well as the server, using Node.JS functions will not work.

Related

I don't know why my http request doesn't work in my angular project?

I created a RESTful API with node.js and when I tested it with postman it worked properly and showed correct result.
But my problem is in request from my angular application. when I send a request, there is no reaction in API and it seems no request is sent to server at all!
My API url is:
http://localhost:3000/api/menus/menujsonexport
And when I send a request via postman it return a json correctly.
And here is my request script in angular:
private requestMenu(type: 'listsidemenu'): Observable<any> {
let base;
if (type === 'listsidemenu') {
base = this.http.get<any>('http://localhost:3000/api/menus/menujsonexport'
, { headers: { Authorization: `Bearer ${this.getToken()}` }});
}
const requestMenu = base.pipe(
map((data: any) => {
return data;
})
);
return requestMenu;
}
I called the request with this method :
public fetchjsonmenu() {
this.authserv.listSideMenu()
.pipe(
finalize(() => {console.log('finished'); }),
tap(x => {
console.log(x);
})
);
}
But there is no reaction in my nodejs API.
Do you have any idea?
Please tell me if there is lack of information to answer to this question.
An Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the response.
.subscribe is not an Angular2 thing.
It's a method that comes from rxjs library which Angular is using internally.
If you can imagine yourself when subscribing to a newsletter and after subscribing, every time that there is a new newsletter, they will send it to your home (the method inside subscribe gets called).
That's what happens when you subscribing to a source of magazines ( which they call it Observable in rxjs library)
All the AJAX calls in Angular is using this library behind the scene and in order to use any of them, you've got to use the method name, e.g get, and then call subscribe on it, because get returns and Observable.
Also, when you're doing this <button (click)="doSomething()"> Angular is using Observables behind the scene and subscribes you to that source of thing, which in this case is a click event.
Back to our analogy of Observables and newsletter stores, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe from them which for that to happen you've got to remember the subscription number or id, which in rxjs it would be like :
let subscription = magazineStore.getMagazines().subscribe(
(newMagazine)=>{
console.log('newMagazine',newMagazine);
});
And when you don't want to get the magazines anymore:
subscription.unsubscribe();
Also, the same goes for
this.route.paramMap
which is returning an Observable and then you're subscribing to it.
My personal view is rxjs was one of the greatest things that were brought to JavaScript world and it's even better in Angular.
There are 150~ rxjs methods ( very similar to lodash methods) and the one that you're using is called switchMap
You need to add .subscribe() in your code after the get call.For more information check the link.
So, now your script should look something like this.
let base;
if (type === 'listsidemenu') {
base = this.http.get<any>('http://localhost:3000/api/menus/menujsonexport'
, { headers: { Authorization: `Bearer ${this.getToken()}` }}).subscribe();
}
const requestMenu = base.pipe(
map((data: any) => {
return data;
})
);
return requestMenu;
}```

How to get JSON from REACT JS to implement in NODE js

I am trying implement REST API using REACT AND NODE. How to get JSON from front end(REACT JS)drag and drop images in template ex."https://www.canva.com/templates/" to store JSON in Mongodb using NODE JS.
Thanks in advance
You can use fetch api to call a particular route and send data along with it to nodejs backend.
You just need to do simply like this:
async function sendData(){
let res = await fetch(url, {
method: 'POST',
mode: 'CORS',
body: {}, //the json object you want to send
headers: {}, //if required
}
)
}
Hope this helps!
Since you asked how to send JSON to node.js I'm assuming you do not yet have an API that your front end can use.
To send data to the back end you need to create an API that accepts data.
You can do this quickly and easily using express.js.
Once the server is running and it has an endpoint to send data to, you can create a request (e.g. when sending data it should be a POST request).
This can be done in many different ways, although I would suggest trying axios.
Hope this helped.
Check the example to get the Json value and update it.
axios.get('https://jsonplaceholder.typicode.com/todos/'+ this.props.id + '/')
.then((res) => {
this.setState({
// do some action
});
})
.catch(function (error) {
console.log(error);
});

How to open web brower by using AWS post lambda

I have written the piece of code below:
static async postSearchResult(httpContext: HttpContext, injector: Injector) {
const log = injector.get(Log);
const service = injector.get(Service);
try {
let result = await service.redirectToUI(JSON.parse(httpContext.getRequestBody()));
httpContext.ok(result, 200, {'Content-Type': 'application/json'});
} catch (e) {
httpContext.fail(e, 500);
}
}
protected redirectToUI(response: any) {
// If any post api call happened then it should open web browser and pass some field as query parameter
window.open("https://www.google.com?abc=response.abc");
return response ? response : "failed";
}
Here I am getting the following error :
Execution failed ReferenceError: Window is not defined
What am I doing wrong?
What you are trying to accomplish doesn't make much of a sense. Lambda is a back-end service. To open new browser window, you need to use front-end JavaScript, not back-end Node (on the back-end, you have no access to the front-end window object).
If you want to open a new browser window as a reaction to some back-end response, then you can send some indicator in the HTTP response (i.e shouldOpenNewWindow: true as a part of the response object), parse that response on the front-end and it the indicator is present, then you can issue window.open command. But it has to be done on front-end.

Using cookies with axios and Vue

I have created a Node.js express server that connects to Salesforce.com using the SOAP interface provided by 'jsforce'. It uses session cookies for authorization via the 'express-session' package. So far, it has a POST method for login and a GET to perform a simple query. Testing with Postman has proven that this server is working as expected.
As the browser interface to this server, I have wrttien a Vue application that uses axios to perform the GET and POST. I need to save the session cookie created during login POST then attach attach the cookie to subsequent CRUD operations.
I have tried various methods to handle the cookies. One method I have tried is using axios response interceptors on the POST
axios.interceptors.response.use(response => {
update.update_from_cookies();
return response;
});
The function 'update_from_cookies' attempts to get the cookie named 'js-force' but it does not find it although I know it is being sent
import Cookie from 'js-cookie';
import store from './store';
export function update_from_cookies() {
let logged_in = Cookie.get('js-force');
console.log('cookie ' + logged_in);
if (logged_in && JSON.parse(logged_in)) {
store.commit('logged_in', true);
} else {
store.commit('logged_in', false);
}
}
I have also seen various recommendations to add parameters to the axios calls but these also do not work.
I would appreciate some advice about how to handle cookies using axios or some similar package that works with Vue
Thanks
The problem has been resolved. I was using the wrong syntax for the axios call
The correct syntax has the {withCredentials: true} as the last parameter
this.axios.post(uri, this.sfdata, {withCredentials: true})
.then( () => {
this.$router.push( {name : 'home' });
})
.catch( () => {
});

React server side rendering with backend requests

I have an React app with server side rendering via Express. I have simple App component:
import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
data: []
};
fetch('http://backend', {
mode: 'cors',
})
.then(res => res.json())
.then(data => this.state.data);
}
render() {
return (
<ul>
{this.state.data.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);
}
};
The problem (or more probable feature) is that fetch works async. So browser gets page with empty data.
Is there a way to get from server page with loaded data? Let's say I want to get from server page with loaded posts or something else.
Or do I something wrong at all?
You are not setting the state correctly. Use setState() to set the new state as you cannot update the state without using setState() method: https://facebook.github.io/react/docs/react-component.html#setstate
fetch('http://backend', {
mode: 'cors',
})
.then(res => res.json())
.then(data => this.setState({data: data}));
Also, the code you have added is not server-side rendering using React. You use the method ReactDOMServer.renderToString() to do server-side rendering: https://facebook.github.io/react/docs/react-dom-server.html#rendertostring
Yes, even if you fix the setState() problem you will still be rendering the component before the fetch. The problem is indeed that fetch is asynchronous.
To be able to server-side render back-end calls you need to wait until all backend calls have been made, set the props & state for all components and then render them out.
Two libraries that will help you with figuring out when things are done are Redial (https://github.com/markdalgleish/redial) and redux-promise-counter (https://github.com/bitgenics/redux-promise-counter) if you are using Redux. More on that below.
The next problem you want to solve is getting that data to the client and initialize your components from that, so you don't have to redo (all) the request(s) on the client again.
You could do all that manually, but if you are serious about SSR, you should probably go for something like Redux. A way to store all your application state in one store. Makes it easier to store results, ship it to the client and initialize your store from JSON.

Resources