How To Overcome CORS issues with Redux React Express and Node? - express

I have a React App that uses React Router and Redux as its state manager. The server side of the app uses Express and Node.
I am making API calls to an external service. I do not have the ability to enable CORS on the external service. Therefore, I need to use my app's server side to make the calls to the external service to remove the browser from the equation, and eliminate any CORS error.
I am able to get my data from the service on the server side successfully. I would like to know if it is possible to share the Redux store in between the client and server with some sort of middleware (looking for examples/resources).
The goal:
1) Handle a click event in the client
2) Have that event call a server side route to external api (don't know how to do this)
3) Then the server handles this route, makes the request, and sends the response to the client (through the shared react store - not sure if this is possible)
4) The store gets the new state, and then sends to the client side components, and the UI updates
Are there any examples/tutorials of this? Not looking for an initial server rendered page, but guides that inform how the above 4 steps can generally be implemented.

Thanks for the suggestions.
It turns out that I was severely over thinking the solution. All I really needed was the ability to launch a server side function (get resources from external API) from the client side event (load component). Sort of like how submitting a form, has an action that launches a server side function.
In my component:
componentDidMount() {
const product_api_results = productApi.getProductItems()
console.log('product_api_results in CART Component: ', product_api_results)
/* now I have results and can put it in the Redux Store via action to reducer for other components to work with on client */
}
The productAPI.getProductItems() that the component calls:
export function getProductItems () {
return axios.get('/api/get-products') // triggers a server side route
.then(function (response) {
console.log('client side response: ', response)
return response
})
}
In Express server.js file, the server will see this url and then get the proper data. The shopify.get() is from the shopify-node-api module:
app.get('/api/get-products', function (req, res) { // '/api/get-products' called from client
shopify.get('/admin/products.json', function (err, data, headers) {
res.send(data)
})
})

Related

How to judge the success of third-party authentication?

My front-end is built with vue, and the back-end is with golang. My questions are 1. When I click the button to request a third-party login, how do I judge that the third-party authentication is successful? 2. And how do I get the data on the server side
The second question I think of is to save data on the server side through cookies and session, and the front end can get information through the cookie HTTP request header. Is there a more concise way
The second question, how can I judge the success of the third-party authentication?
My jump Url code is
/// vuex
async accountLoginAction({ commit, dispatch }, payload: any) {
const from: string = payload
window.location.href = getMixinUrl(from)
},
Through this code, the page can be jumped to a third party, then how can I judge that the authentication is successful? And how to request data gracefully when the judgment is successful.

Playwright intercept server side network request

Can't see to find any good docs on how to mock/stub the server Sider side requests with playwright.
An example would be to intercept the getServerSideProps in nextjs: hitting the routes makes the server do a request (db API etc). Then it can do some business logic (which should also be covered by testing) before it is passed to the component as props which is sent to the client (being server side rendered).
Mocking that db API request without having some test logic mixed into the business logic is what I am hoping to find an answer for.
Playwright allows you to do interception and mocking/stubbing.
UI action can triger the API call, and without sending request you can intercept
the response.
And you can use moks and stubs as well.
const mock = { animals: [] }
await page.route('**/Zoo/v1/books', (animals) =>
route.fulfill({
status: 304,
body: JSON.stringify(mock),
})),
);
await page.goto('https://www.demoqa/animals');
See more https://github.com/microsoft/playwright/issues/1774#issuecomment-769247500
And https://playwright.dev/docs/next/network#modify-responses

How to handle backend auth with express as reverse proxy api

I am using express the first time in a project as a kind of reverse proxy in between my frontend and backend. The backend authentication is cookie based.
First I was using http-proxy-middleware to make my requests. This works fine and the cookie gets passed no problem.
The problem is that I want to decouple the front and backend as the api isn't very usable right now (for example 3 requests necessary to get data for one view). So instead of making requests directly I want to have my express server handle the heavy lifting in the background.
Currently I am using axios for the requests and pass the cookie through with the request and the new one back with the response. This works fine but feels very hacky and error prone. For example I have to split the returned setcookie string in a very weird way.
app.get('/api/myrequest', (req, res) => {
axios.get('backendserver/url', {
headers: {
Cookie: req.cookies['auth'],
},
responseType: 'json',
})
.then((response) => {
let tempCookie = response.headers['set-cookie'][0];
tempCookie = tempCookie.split(';')[0];
tempCookie = tempCookie.split('=');
res.cookie(tempCookie[0], tempCookie[1]);
res.send(response.data);
})
});
I suppose there is a much better way to handle this. I was looking at things like passportjs but am not sure if it fits this special use case as the auth isn't handled by express itself.
Maybe someone can point me in the right direction?

How to store data to local storage with Nuxt.js

As you know, nuxtjs is server side rendering and there is no good example how to store data into localstorage which is client side.
My work is need to build login form where user can put username and password into the form the send it to server (via api) to check, if login data is correct, the api will return one token key then I will store this key to verify is user is authen and use it with other api.
I found some example but build with vuejs here https://auth0.com/blog/build-an-app-with-vuejs/ but I don't have an idea how to change it to nuxtjs.
Any I have read https://github.com/robinvdvleuten/vuex-persistedstate which I can plug in to my project but I would like to see other solution.
Regards.
Nuxt provides you with process.client to tell it to execute only on the client side
so use it like this:
methods: {
storeToken(token) {
if(process.client) {
localStorage.setItem("authToken", token)
}
}
}
Check this link for more info.
You can use process.client to check it's on client-side or not.
export default {
created() {
this.storeToken();
},
methods:{
storeToken(token){
if(process.client){
localStorage.setItem("authToken", token);
}
}
}
}
You also call this method in mounted without check process.client.
export default {
mounted() {
this.storeToken();
},
methods:{
storeToken(token){
localStorage.setItem("authToken", token);
}
}
}
A little late to the party, but I was having similar problems.
But first I would recommend you to use cookies for saving a key/token/jwt.
The reason being that localStorage can be hijacked through JS api's and cookies can be safeguarded from that. You will however have to safeguard your token from CSFR.
That can be done by having a look at the Refence and Origin headers server side.
This guy wrote a good post on how to do that: How to protect your HTTP Cookies
As for accessing localStorage from Nuxt, here we go:
If you are running Nuxt and haven't told it to run in spa mode it will run in universal mode. Nuxt defines universal mode as:
Isomorphic application (server-side rendering + client-side navigation)
The result being that localStorage is not defined serverside and thus throws an error.
The give away for me was that console logging from middleware files and Vuex outputted to terminal and not the console in developer tools in the browser.
if you want to read more about my solution you can find it here: localStorage versus Nuxt's modes
If you plan on storing small amounts of data, below 4096 bytes, you can use cookies. I recommend the library cookie-universal-nuxt.
npm install cookie-universal-nuxt --save
nuxt.config.js
modules: [
'cookie-universal-nuxt',
],
Then you can use:
const data = {
anything: 'you want',
}
this.$cookies.set('thing', data, {
path: '/',
maxAge: 60 * 60 * 24 * 7
});
this.$cookies.get('thing');
Read the library docs for more if you need it.
The cookie will be available server-side, so you can get around the issues with localStorage.
Just be aware that cookies can only store up to 4096 bytes per cookie.
For example, I fetch cookie data in the nuxtServerInit function in Vuex, and the data is then available everywhere in the app server-side.
Insofar as client means a web browser, all the options are spelled out in the []HTML Living Standard Web Storage section.
12.2 The API
12.2.1 The Storage interface
12.2.2 The sessionStorage getter
12.2.3 The localStorage getter
12.2.4 The StorageEvent interface
U can work with const page = useState( () => data ) or if u want to use local or session storage u can use VueUse module..
I know its a bit late and it might not be the answer you are looking for...but it could be helpful for someone..what i learned after going through many documentations and other answers is that u just cant use local or session storage. In development it just runs when u change the route but when u refresh the page or the component using session storage it throws error "sessionStorage is not defined"..if u are not planning to store data for long time like u do with session or local...u can work with useState( () => data ) property that nuxt provides..it stores your data until u refresh your webPage...

How to send a POST request response back to client (React component)?

I'm using React to send a post request to my express server which then returns a response, like so:
app.post('/api/games', function(req, res) {
return res.json();
});
Before I use that response to persist it to a database, I want to be able to see everything within that response. When I console.log it from the server, I get a long list of the JSON object printed, but would ideally like something closer to Chrome's dev tools console where I can click through and inspect everything. How can I send this response JSON back to my React component so that I can console.log it in in the browser?
Thanks!
You can use node-inspector in order to debug your express API.
It uses Chrome Dev Tools so you'll feel like you are debugging your client side!
Remember, a request comes in, and the response goes out.
on a request, the req.body and req.params will contain the body/params of the request.
To respond to a request, use the res.json({someJSONHere}) or you can also res.send({someJson})
You can also console.log inside the server and watch output on the terminal
app.post('/api/games', function(req, res) {
console.log(req.params)
console.log(req.body)
return res.json(
Object.assign({}, req.body, req.params)
);
});
Express request/response Documentation
If you want to view your response in the client-tier here are some of the things you can do using the GoogleChrome asides from the console
1 Use React Developer Tools
2 I like using Postman for viewing and manipulating request/response