Axios post request in React JS - javascript

Im on a React JS project and i need to request some data from a server.I want to obtain this information before the render , because i want to show the data on the browser the first time is charged.
This is the code i have written (Before the render() of a Component):
componentDidMount(){
axios.post('https://XXX',{
msisdn:"XXXX",
passwd:"XXXX"
}).then(res=>console.log(res.data))
}
But I obtain the following errors:
Errors obtained after the axios request
My questions are:
How can I solve this problems without modifying the CORS conf on the server?.
I have my react project on a server and i was thinking about if it would be possible to make the request from the server and then send the data or obtaine it from React.
Thanks in advance!

Related

Avoiding Net.createConnection errors in Node

I am currently building an app with React and Node.js
In this app, I need to query a database on my own server with the following function, located in a separate file called "database.js"
const fetchQuery = util.promisify(con.query).bind(con)
// Get all the tracks for a given date from the
const fetchTracks = async (date) => {
const rows = await fetchQuery("SELECT * FROM tracks WHERE playlistDate = '"+date+"'");
}
This works perfectly when I run the file with Node from the command line. However, when I attempt to import it into my react app with
import { fetchTracks, addTracks } from '../scripts/database'
I begin to get errors in the database file, specifically Unhandled Rejection (TypeError): Net.createConnection is not a function on my fetchQuery call.
From what I've read, this happens when attempting to call the function from the browser, as that would pose a security risk. However, as I understand it, all node operations are performed on the server side, right? Why would I be getting this flag when the database is supposedly queried before the page is served? What do I need to do amend this?
React runs in the browser, so as soon as you include database.js in your React app, it's running in the browser with the rest of React, so of course you'll get the error. Making this work gives two options:
expose an API endpoint from Node for React to call, and that API endpoint calls database.js, or,
investigate server-side rendering for React, where some of your React app -- particular the more static parts of it like your main menu -- are created on the Node side and only the final HTML is sent to the browser. (This is a large topic all by itself though.)
By your example which takes a date parameter for the SQL, I'm guessing #2 isn't an option.

How to pass app state in ReactJS to the backend?

I am working on a web app using ReactJS in which I have created a form and stored the values of all the input fields into state of the app. That is, the state of my App.js file contains values of all the input fields created in Form.js file. I want the information stored in state to be passed on to the backend so that I can process a dataset based on it.
How do I add a functionality so that on clicking a submit button everything that's in my app state gets passed on to the backend- say to a text file, or in a json file.
Basically I want to search through a dataset (using Elasticsearch) based on the information provided by a user in the form (using ReactJS).
I am new to React so I don't have much knowledge. I have made the web-app but I need suggestions on how to pass the information that I obtain through the form to a backend so that I can do further work.
How do I add a functionality so that on clicking a submit button
everything that's in my app state gets passed on to the backend- say
to a text file, or in a json file.
You can make a request for data to use in your application using Axios OR Fetch API. You can consume REST APIs using two of the most popular methods known as Axios (a promise-based HTTP client) and Fetch API (a browser in-built web API).
The fetch() API is an inbuilt JavaScript method for getting resources from a server or an API endpoint. It’s similar to XMLHttpRequest
Axios is an easy to use promise-based HTTP client for the browser and node.js. Since Axios is promise-based, we can take advantage of async and await for more readable and asynchronous code. With Axios, we get the ability to intercept and cancel request, it also has a built-in feature that provides client-side protection against cross-site request forgery.
To know more you can refer this
Both these above methods, can be used to submit the data from your front end into the back end, so that the data is stored into the back end, and then you can perform several operations on it according to your requirement.
You can refer several blogs and documentation to know more about this:
Use axios to fetch data from an api in ReactJS
Fetch API for POST Request
Axios
Difference between Axios and Fetch API
Recently, I have also created an application, wherein I am integrating React with SpringBoot application.
In this Application. I have set up router and route, created and submit form, called GET, POST, PUT, DELETE request using axios (have also done with fetch API).
submitBook= event =>{
event.preventDefault();
const book = {
title: this.state.title,
author: this.state.author,
coverphotoURL: this.state.coverphotoURL,
isbnNumber: this.state.isbnNumber,
price: this.state.price,
language: this.state.language
};
const headers = new Headers();
headers.append("Content-Type", "application/json");
fetch("http://localhost:8080/rest/books",{
method:"POST",
body:JSON.stringify(book),
headers
})
.then(response => response.json())
.then((book) => {
if(book){
this.setState({"show":true, "method":"post"});
setTimeout(() => this.setState({"show":false}),3000);
}
else{
this.setState({"show":false});
}});
this.setState(this.initialState);
};
To view the full code, you can refer my Github Repository
You need to look into making XHR or using the fetch API (or axios) to make http requests to the backend API.
use axios for calling api urls that you have defined in the backend. you can watch a short tutorial on youtube to get familiar with the basics.
You may want to use Fetch API documented in MDN. It handles url request, including REST API to parse data over HTTP, e.g. JSON object etc.

Fetching remote data multiple times based on user choice within a page

I am using next js for developing a web app. I have following page:
<page>
<component_1>
Fetch the data from remote server using `getInitialProps` (I could use `getStaticProps` or `getServerSideProps` too)
Show the data to user and get the user input, pass on to component_2
</component_1>
<component_2>
Based on the user selection, fetch remote data and show it in the page
</component_2>
</page>
During user interaction, either component_1 or component_2 is visible.
getInitialProps is allowed to be used only on page level components (URL loading) and not called in sub-components (this way, I am not able to get remote data from component_2). Should I have to handle this scenario by using different URLs? Or is there a better way of handling in the same page?
Thanks for the help in advance!!!
getStaticProps, getInitialProps and getServerSideProps are functions that fetch data for pre-rendered pages and components.
Your component needs to fetch data based on the user actions, so you need to fetch data only on the client side. You can fetch data on the client side in any React component.
Example using SWR hook. However, you can use any preferable method to fetch data.
import useSWR from 'swr'
function Profile() {
const { data, error } = useSWR('/api/user', fetch)
if (error) return <div>failed to load</div>
if (!data) return <div>loading...</div>
return <div>hello {data.name}!</div>
}
Suggested reading: Next.js fetching data on the client side

ReactJS - Handle POST requests using react router dom

Is there a way to handle POST requests using the react-router-dom (npm) library?
Why? The payment gateway will redirect the user, who successfully payed, back to the platform. I can use a GET or POST request to transfer data with the redirection page. But I don't like having the data visible in the URL. Other options are always welcome, I'm using a REST API (Node.JS, Express) and a website/dashboard (ReactJS)
I get what you're after but you can't POST to the browser. If you're uncomfortable passing data as GET params in a URL, you could:
store data in LocalStorage when user submits
deliver server-rendered, static HTML upon redirect that contains purchase information
asynchronously get user's purchase data upon page load with AJAX or fetch() (or your favorite data-grabbing util).
Since you're in a React world, I'd recommend the third option here. How to fetch data, build an API endpoint, store data, then display it goes well beyond the scope of this question so I'd suggest some Googling. Here's a starting point: https://code.tutsplus.com/tutorials/introduction-to-api-calls-with-react-and-axios--cms-21027
You can handle the POST request on your express server then redirect to a static page of your app :
app.post('/payment_webhook', (req, res) => {
const paymentOk = req.body.payment // handle POST data
if (paymentOk) {
res.redirect('http://app.com/payment_success');
} else {
res.redirect('http://app.com/payment_failed');
}
});
I was discussing the same with a friend and so far we saw 2 ways of doing this:
let the payment gateway return_url be an endpoint of the backend API (rails api), which will do the commit to the payment gateway (and probably updating the order in the BD), and then it will do a redirect back to your frontend app
store the gateway trasaction token on the order object in the DB, and let the payment gateway return_url to return to a dynamic order url, therefore, react will now which order should render, then asynchronously ask the backend (rails service) to extract the token from the order object and do the commit (confirmation) and update it's status and return the order object back to react, then react can now show if the order was successful or not.
we opted for option #2, since I feel that the frontend (react) shall be the main communication gateway to our system, and the only one communicating to the backend shall be the frontend.
UPDATE: option #2 did not work since you cant do POST to a react-app therefore, we make the return_url to be dynamic, and we immediately redirect to the frontend with a url with the order_id as query param, then, the frontend when tries to load the order, in the backend we do the payment gatway confirmation, update the order object and return the updated order object to the frontend

Nextjs global api calls

I am developing react based web application using NEXT.js,. As specified in NEXT.js, documentation to fetch the data before page loads, i am putting required action dispatch code in getInitialProps of the specific page. but some data fetching calls(action dispatch) like fetching authenticated user's data will be common to all the pages, so is there any way to dispatch such actions from single place before page load.
Thanks!
update, now you can use getServerSideProps and nextjs provides an easy way to get user cookie : How to use cookie inside `getServerSideProps` method in Next.js?
--------- old answer ---------
simple answer: use cookie, code refer https://github.com/nextjs-boilerplate/next.js-boilerplate https://github.com/nextjs-boilerplate/next-fetch
-- details --
I had the same question when I first adopt next.js, as it worked in react, people prefer use a token to tag authed user and fetch always run in front-end. But as next.js made ssr a build in feature, I tried and find auth by cookie is possible, and I start https://github.com/nextjs-boilerplate/next.js-boilerplate and split out a fetch based on cookie https://github.com/nextjs-boilerplate/next-fetch
-- how it works --
1.client side fetch: use fetch option option.credentials = 'include' and option.headers.Cookie=document.cookie will patch cookie into your request. Bnd when fetch back result, this become wired, you cannot access cookie header, so you have to use another header and additional logic needed in backend logic like res.header('custom-set-cookie', res.getHeader('set-cookie'))
2.server side fetch: first you need the express request object, and get cookie like req.headers.cookie, then pack it into fetch request option. when fetch back, get cookie like r.headers._headers[cookieHeaderName] and pack into response res.header('set-cookie', setCookie)
then after you pack this transfer up, you can simply call a json api and cookie will automatically transfered. And if you don't need to change cookie through header (you can through js), you can ommit the extra handle like res.header('custom-set-cookie', res.getHeader('set-cookie')) in api
you can try my ssr login here http://nextjs.i18ntech.com/login

Categories