How to send data from react to nodejs without localhost? - javascript

I am trying to deploy reactjs & nodejs app to heroku.
I have successfully deployed frontend,but frontend is sending data to nodejs using localhost due to which when running app through heroku only frontend is working.
This code send data to nodejs.
saveUserJson = (User) =>{
const url = 'http://localhost:5000/write'
axios.post(url,User)
.then(response => {
//console.log(response);
});
}
This is nodejs code(ignore hostname in code).
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const morgan = require('morgan');
const cors = require('cors');
const jsonData = require('../src/descriptors/bnk48.json')
const app = express();
const port = 5000;
const hostname = '192.168.43.113';
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());
app.get('/',(req,res) => res.status(200).send({
message: "Server is running..."
}));
const WriteTextToFileSync = (contentToWrite) => {
fs.writeFileSync('./src/descriptors/bnk48.json',contentToWrite,(err) =>{
//console.log(contentToWrite);
if(err) {
console.log(err);
}else {
console.log('Done writing to file successfully...')
}
})
}
const user = {
}
app.post('/write',(req,res,next) =>{
const user = {
"name": req.body[0].name,
"descriptors": req.body[0].descriptors
}
jsonData[user.name]=user
//console.log(req.body[0].descriptors)
const requestContent = JSON.stringify(jsonData,null,2);
WriteTextToFileSync(requestContent)
});
app.use((req,res,next) => res.status(404).send({
message: "Couldn't find specified route that was requested..."
}));
app.listen(port,hostname,()=>{
console.log(
`
!!! server is running..
!!! Listening for incoming requests on port ${port}
!!! Server running at http://${hostname}:${port}/
!!! http://localhost:5000
`
)
})
How can i change localhost so that while deploying it automatically chooses where to send data?

How can i change localhost so that while deploying it automatically chooses where to send data?
There are several ways to do this, but it's quite common to use environment variables for this purpose. These are set by environment, your development machine being one environment and your production site on Heroku being another environment. You could for example define the environment variable BACKEND_ROOT_URL to hold the schema and FQDN of your site, and make your axios call like this:
saveUserJson = (User) =>{
const url = `${process.env.BACKEND_ROOT_URL}/write`
axios.post(url,User)
.then(response => {
//console.log(response);
});
}
The build-time value of url will be different, depending on which environment you perform the build in.
Setting environment variables locally can be done in several ways. In a Bash shell you can set them manually like export BACKEND_ROOT_URL=http://localhost:5000. That get's boring quite fast though, so I would recommend you to check out dotenv which handles this for you efficiently.
Heroku has its own way of handling the setting of envvars - check the documentation here

Related

Cookie not showing up in browsers development tool application?

I am working on a web app project and for which i need to authenticate the user for some protected routes so i am using jwt tokens for this need.
Technologies used in project :-
frontend --> react
backend --> node, express
Node JS backend code.
const express = require('express');
const app = express();
const ProductModel = require('../Schemas/productSchema')
const product = ProductModel;
app.get('/', (req, res) => {
try {
product.find(function(err, data){
if(data){
res.cookie("test", "test1");
res.send(data);
}
else{
res.json({message : err});
}
})
} catch (error) {
res.json({message : error});
}
})
React frontend code.
here in this frontend code i am making a get request to the server using fetch
useEffect(() => {
async function fetchData(){
await fetch('http://localhost:5000/products')
.then(res => res.json())
.then(data =>{
// setProducts(data.data);
})
.catch(err => console.log(err))
}
fetchData();
}, [])
In the nodejs code i am sending cookie to the browser and for good the cookie is getting shown in the chrome devtool network
But cookie is not getting shown up in the browser->devtool->application->cookies
I don't know why this happening please submit the solutions with explanation.
First, I guess that u need to import the cookie parser
const cookieParser = require('cookie-parser')
app.use(cookieParser());
this lets you use the cookieParser in your application
And finally u can use it :
res.cookie(`...`);

How to use data returned from an HTTP request using http-proxy-middleware and Express

I am making API calls to Squarespace for an inventory management system. I've set up a Node.js and Express server, and have been using http-proxy-middleware to set up a proxy and make GET requests.
I am able to generate the GET requests successfully on my localhost - an HTML pre-tag is filled with all of the JSON data of the request. However, I am completely clueless on how to handle and use the data further that was returned to me. When I make a call and receive Pending orders, I want to pull JSON data from the returned request body of the orders, such as SKU numbers for products purchased.
const { response } = require('express');
const express = require('express');
require("dotenv").config();
const { createProxyMiddleware, responseInterceptor } = require('http-proxy-middleware');
const router = express.Router();
const PORT = 3000;
const HOST = "localhost";
const GET_ORDERS_URL = process.env.SS_GET_ORDERS_URL;
const API_KEY = process.env.SS_AUTH;
const app = express();
const proxy = app.use("/testing", createProxyMiddleware({
target: GET_ORDERS_URL,
headers: {
'Authorization': API_KEY,
'User-Agent': 'halp me'
},
changeOrigin: true,
pathRewrite: {
[`^/testing`]: '',
},
selfHandleResponse: true, //
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
var orderResponse = responseBuffer.toString('utf-8');
return orderResponse;
}),
}));
// Start Proxy
app.listen(PORT, HOST, () => {
console.log(`Starting Proxy at ${HOST}:${PORT}`);
});
The API request returns JSON data, which I would love to use and process for the next part of my inventory management. I'm trying to figure out why I can't get return orderResponse; to output anything at all.
I have tried every variation of returning a variable I can imagine, console.logged a million things - any guidance to what I'm missing here would be greatly appreciated!

TypeError: Cannot read property 'execute' of undefined . node.js how to export oracle db connection

Hi I am new to node and oracle.I have created a app and made a successfull connection to db.
I need to use connection object across the application how can i do that?
Below is my index.js file
const express = require("express");
const app = express();
const authRoute = require("./routes/auth");
app.use(express.json());
app.use("/api",authRoute) ;
app.listen(3000,function(){
console.log("Node Server : Running on port 3000...");
})
database connection file => connect.js
const oracledb = require('oracledb');
const dotenv = require('dotenv');
dotenv.config();
const connection = oracledb.getConnection(
{
user : process.env.USER,
password : process.env.PASS,
connectString : process.env.ConnectString
},
function(err, connection)
{
if (err) {
console.error(err.message);
return;
}
console.log('Connection was successful!');
connection.close(function(err){
if (err) {
console.error(err.message);
return;
}
});
});
module.exports = connection;
I want to use this db connection in my auth.js file
const router = require('express').Router();
const db = require('../database/connect');
router.post("/authenticate",function(req,res){
//console.log(req);
const user = req.body.username;
const username = {"name" : user};
const pass = req.body.key;
const password = {"pass" : pass};
//const result = db.execute('select * from usertable');// this doesn't work
//console.log(result.rows);
res.send('success');
});
module.exports = router;
when i run const result = db.execute('select * from usertable'); I get the error below.
TypeError: Cannot read property 'execute' of undefined
What am i doing wrong.Can anyone please help.Thanks in advance
I had faced this problem. You must install Oracle install client v 19 in your machine. You have to go to web install oracle instant client base on your machine.
(Update: there is a multi-part series with code showing what you want at https://github.com/oracle/oracle-db-examples/tree/main/javascript/rest-api)
Use a connection pool that is opened at app start. Then the pool cache can be used to get the pool (and then connections) in other modules.
For a web app like yours you definitely want to use a connection pool for performance.
There's a big section on connection pooling in the documentation. E.g see Connection Pool Cache which says:
When pools are created, they can be given a named alias. The alias can
later be used to retrieve the related pool object for use. This
facilitates sharing pools across modules and simplifies getting
connections.
The examples are worth reviewing.

next.js app with custom server is not rendering correctly

I'm new to next.js so maybe I'm missing something very stupid. I want to use custom routes so I created a server.js file and changed my package.json command to node server.js. This is the entire server.js file:
const express = require("express");
const next = require("next");
const createLocaleMiddleware = require("express-locale");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app
.prepare()
.then(() => {
const server = express();
server.get("/", createLocaleMiddleware(), (req, res) => {
res.redirect(`/${req.locale.language}/home`);
});
server.get("/:lang/home", (req, res) => {
const actualPage = "/";
const queryParams = { locale: req.params.lang };
app.render(req, res, actualPage, queryParams);
});
server.listen(3000, err => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
})
.catch(ex => {
console.error(ex.stack);
process.exit(1);
});
I believe that according to the docs, this should work. I just want to render the index page with the users locale on the specified route ('/:lang/home'). I'm using react-intl for the i18n.
Now I get the following error in the console (client side):
It's in dutch but it's just saying it can't find any of the specified files. So now the HMR is not working anymore, routing is not working anymore (with Router.push). The only thing it does correctly is loading the index page (I can see it in the browser).
I also tried to enable and disable this flag from the docs:
module.exports = {
useFileSystemPublicRoutes: false
}
Sadly, no effect.
Am I missing something? Is it because I'm redirecting? Or is this not to way to handle routing? If someone could provide some pointers that would be great :)
Thanks in advance!
You are missing server.get('*', handle) as you can see in the custom server express example. This is absolutely required :)

Cloudkit JS && Node JS

I'm currently trying to perform server side connection to iCloud Server using the new CloudKit JS from Apple. According to the WWDC 2015 "CloudKit JS and Web Service", since CloudKit JS is a pure JS framework, you can use it in all JS environnements such as node JS.
I copied the source code of CloudKit JS from https://cdn.apple-cloudkit.com/ck/1/cloudkit.js and pasted it in a file named "cloudkit.js". Here is a demo of what I tried :
var CloudKit = require("/some/folders/cloudkit.js")
function demoPerformQuery() {
CloudKit.configure({
containers: [{
containerIdentifier: 'myContainerIdentifier',
apiToken: 'myAPIToken',
environment: 'development'
}]
})
var container = CloudKit.getDefaultContainer();
var publicDB = container.publicCloudDatabase;
publicDB.performQuery({recordType: 'Items'}).then(function(response){
// never called :-(
})
}
var express = require('express')
var app = express()
app.get("/", function(){
demoPerformQuery()
})
var server = app.listen(8080, function () {
console.log("server launched")
})
CloudKit seems to be correctly set up since all the functions are correctly called. But the callback of performQuery is never called. Why ?
Is there someone who already succeed to configure CloudKit JS in an server environnement ?
Thanks in advance
In the browser, CloudKit.js relies on XmlHttpRequest in order to fetch resources, but since CloudKit isn't an npm module you'll need a way to fetch things from your server.
npm install node-fetch
Using node-fetch, here is a tweaked version of your code that logs the resulting Items in your query:
var fetch = require('node-fetch');
var CloudKit = require("./cloudkit.js")
CloudKit.configure({
services: {
fetch: fetch
},
containers: [{
containerIdentifier: 'yourContainerIdentifier',
apiToken: 'yourAPItoken',
environment: 'development'
}]
})
var container = CloudKit.getDefaultContainer();
var publicDB = container.publicCloudDatabase;
function demoPerformQuery() {
publicDB.performQuery({recordType: 'Items'}).then(function(response){
console.log(response)
}).catch(function(error){
console.log(error)
})
}
var express = require('express')
var app = express()
app.get("/", function() {
demoPerformQuery()
})
var server = app.listen(8080, function () {
console.log("Server listen")
})
After hitting http://localhost:8080 you should see your server log the response to your query.

Categories