I recently tried to deploy json-server to my interserver's shared hosting plan via cPanel.
I uploaded the app and configured a Node.js app and I'm able to access the endpoint via 'https://soltonbaev.com/json-server/api/contacts' however the jsonServer.rewriter() is not rewriting the "/api/" route to the "/".
In addition I cannot access the individual object via it's id, like for instance "https://soltonbaev.com/json-server/api/contacts/1". Server returns 404.
So clearly, JSON server is not picking up the routes when it is supposed to.
Here is the content of my server.js file
require('dotenv').config();
const jsonServer = require('json-server');
const cors = require('cors');
const server = jsonServer.create();
const router = jsonServer.router('database.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;
server.use(
jsonServer.rewriter({
'/api/*': '/$1',
})
);
server.use(cors({origin: process.env.REMOTE_CLIENT_APP, credentials: true}));
server.use(middlewares);
server.use(router);
server.listen(port, () => {
console.log(
`🚀 JSON Server is running on ${process.env.REMOTE_CLIENT_APP}:${port}}`
);
});
Related
I trying to open a local website on my local network that I can access from every devices in my network.
I use React as frontend, Nodejs as backend and mongodb is my database(Locally).
On the computer where everything is running I can enter the site through my address on the local network and see the data that is in the database, but as soon as I enter the site through another computer that is on the same network I see the site but not the data from the database.
How i can fix this ?
I use this code for the node js server and run node server in terminal:
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const ip = require('ip');
const app = express();
require('dotenv').config();
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri);
const connection = mongoose.connection;
connection.once('open', () => {
console.log('MongoDB database connection established successfully');
});
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.use(express.static('../build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve('../build/index.html'));
});
const PORT = process.env.PORT || 3000;
console.log('server started on port:', PORT, ip.address());
app.listen(PORT,"0.0.0.0");
First thing is to specify the react HOST. If you're using create-react-app, Simply run HOST=your_ip npm run start.
To get this your_ip, run ifconfig on unix systems, and you'll find the IP for the your PC on the LAN you're connected to.
For the nodejs side, you might need to try something like
server.listen(80, 'current_local_ip');.
I am trying to build a full stack app using ReactJS for the frontend and ExpressJS for the backend. I use Axios to make calls from my frontend to my backend. When I make those calls, I get these errors:
My express index file:
const express = require('express')
const path = require('path')
var app = express()
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
My get call from React frontend:
componentDidMount() {
axios.get("http://localhost:5000/servers.json").then((res => {
this.setState({ servers: res.data })
}))
}
React server is running on port 3000 and Express server is running port 5000, so there shouldn't be a conflict there...
The reason you are getting the error http://localhost:3000 is not allowed by Access-Control-Allow-Origin is because of the same origin policy, a security feature that's restricting your react script from accessing/communicating your server since they are from different origins. Please note that for documents or scripts to be considered as having the same origin they need to have the same protocol (e.g http / https), hostname (e.g localhost / www.my-server.com) and port. In your case port the react script runs at port 3000 while the express script is running on port 5000, thus the error.
To solve this, you need to enable CORS - Cross Origin Resource Sharing on your server side code. First install the cors dependency using the command
npm install cors
Then update the code in your server to look as follows:
const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
Hopefully this works for you.
This looks like a basic cors issue. Add this cors middleware to your express server. It's the state of the art solution to this problem.
const express = require('express')
const path = require('path')
var cors = require('cors')
var app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
If you are interested about cors in general, check out the wikipedia page.
I have done npm install swagger-ui-express in the root folder of the project and kept a swagger.json as well there. My app.js contains:
var swaggerUi = require('swagger-ui-express'),
swaggerDocument = require('./swagger.json');
const express = require('express');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// app.use('/api/v1', router);
const server = app.listen(3000, function () {
let host = "localhost"
let port = 3000
console.log("App listening at http://%s:%s", host, port)
})
I have created a folder api-docs as well inside the root project folder. When I run in terminal node app.js and see in the browser localhost:3000, it displays
Cannot GET /
What can be the issue?
I am a beginner to MERN stack and I deployed my nodejs app to heroku but the app is unable to connect to mongodb atlas and data from the database does not load when I give the mongodb uri via an environment variable.It works fine when I directly give the uri via a variable.Also when run locally,the app connects to atlas without any problem using environment variable.Any idea why its not working on heroku and how to fix it?
server.js
const express = require('express'); //nodejs framework for creating web apps
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
require('dotenv').config(); //for setting environment variables on server
const app = express(); //creating the app
//Serve static assets if in production
if(process.env.NODE_ENV ==='production'){
//Set static folder
app.use(express.static('client/build'));
app.get('*',(req, res) => {
res.sendFile(path.resolve(__dirname,'client','build','index.html'));
});
}
////////////////////////////////////////
const port = process.env.PORT || 5000;
app.use(cors()); //for cross origin resource sharing ie.cross domain requests
app.use(express.json()); //for handling json data
const uri = process.env.ATLAS_URI;
//its works fine when I give it as below
//const uri="mongodb+srv://jose:<password>#exercisecluster-rmqkg.gcp.mongodb.net/test?retryWrites=true&w=majority"
mongoose.connect(uri,{ useNewUrlParser: true, useCreateIndex: true ,useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('Database connection established successfully');
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
//executes the files in the second argument when user enters the url 'rooturl/firstargument'
app.use('/exercises',exercisesRouter);
app.use('/users',usersRouter);
app.listen(port,() => {
console.log(`Server is running on port:${port}`);
});
In your heroku project you need to setup an env variable ATLAS_URI and enter the value for your mongodb uri.
To do so go to the settings tab in your heroku app, then click on reveal config vars, and then enter the key and value for your mongo uri.
Hope this helps
I have created an app engine basic server and connected it for Firebase:
// server.js
// Express packages
const express = require('express');
const app = express();
const path = require(`path`);
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
// Firebase packages
var firebase = require('firebase');
var firebaseConfig = {...};
var fire = firebase.initializeApp(firebaseConfig);
var ref = firebase.database().ref('test');
ref.on('child_added', readMessage);
function readMessage(data) {
console.log('data', data)
};
// Route index
app.get('/', (req, res) => {
res.send('Hello from App Engine!');
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
My idea was to trigger this service (not sure which route, but I guess it is open?) when a child is added to the node test on Firebase.
To give a bit of background information, I am basically planning to create a peer connection using webrtc and then parse the video on this nodejs server. I use Firebase for signallin by sending the webrtc information to the node test and then the server can read and process this once there is a change.
I do not understand however how to trigger this service when a child is added (thus when I send some meta data to the node test in Firebase). How do I structure my nodejs code to handle this? Or should this be done differently?
Using cloud function with Firebase Realtime Database triggers, we can call the app engine endpoint using http or Cloud Tasks.