I have deployed my application (created with npm run build) to heroku. However, the api calls done on heroku production are from my localhost. How do I change this? Could anyone please advice?
api_axios.js
const axios = require('axios')
export default () => {
return axios.create({
baseURL: 'https://myapp.herokuapp.com/api/' || 'http://localhost:1991/api/'
})
}
server.js
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 1991
// express app
const app = express()
// middleware
app.use(cors())
// routes
const metrics = require('./routes/api/metrics')
app.use('/api/metrics', metrics)
// handle production
if(process.env.NODE_ENV === 'production'){
// static folder
app.use(express.static(__dirname + '/public/'))
// handle spa
app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'))
}
// run server
const server = app.listen(port, ()=>{
console.log(`server running on port ${port}`)
})
Just like you check process.env.NODE_ENV in your server, you should also check environment when you compile your JavaScript.
You can use environment variables (via process.env as above), configuration files (such as require('./config.json'), or any other method you like. At the end of the day though, you shouldn't hardcode your API URL.
Related
I have two projects. First a single page app (without bundler) which is being started by the following server.js:
const express = require("express");
const morgan = require("morgan");
const path = require("path");
const DEFAULT_PORT = process.env.PORT || 8000;
// initialize express.
const app = express();
// Initialize variables.
let port = DEFAULT_PORT;
// Configure morgan module to log all requests.
app.use(morgan("dev"));
// Setup app folders.
app.use(express.static("app"));
// Set up a route for index.html
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
// Start the server.
app.listen(port);
console.log(`Listening on port ${port}...`);
Secondly, I also have a separate Express application which handles authentication and has multiple routes and templates/views. However, I want one of those routes to contain the single page app instead of a simple view. I copied the whole repository of my first project into the Express applications src-directory and would now like to make it available under the route "/app".
Is that possible? How would I make sure that the static files of the single page app are being used properly?
router.js of the Express application
const getRoutes = (mainController, authProvider, router) => {
const authorizationMiddleware = require("./authorizationMiddleware");
// app routes
router.get("/", (req, res, next) => res.redirect("/home"));
router.get("/home", mainController.getHomePage);
router.get("/app", (req, res) => {
???
});
...
project structure:
-src
--first projects dir
--data
--msal-express-wrapper
--public
--utils
--views
--app.js
--authorizatonMiddleware.js
--controller.js
--router.js
-appSettings.js
-package.json
-...
Here, I'm trying to render images that are in backend/uploads/images.`
this is my backend server.js file
const express = require("express");
require("dotenv").config();
const cors = require("cors");
const { v4: uuidv4 } = require("uuid");
const app = express();
const postRoute = require("./routes/postRoute");
const userRoute = require("./routes/userRoute");
const DbConnection = require("./db/db");
DbConnection();
app.use(cors());
app.use(express.json());
app.use(express.static("uploads/images"));
app.get("/", (req, res) => {
res.send("Home server");
});
app.use("/api", postRoute);
app.use("/api/users", userRoute);
app.listen(process.env.PORT || 5000, () => {
console.log("Server started");
});
`
this is my ui where i want to pull the image as title("hello") and content("sadsaassa") is being pulled from mongodb.
this is how i tried to pull the image
<img
src={../../../../backend/uploads/images/${detailedArticle?.imageUrl}}
/>
Can anyone help me?
Since Nodejs and Reactjs are running in different server, you have to access images over http something like this..
http://localhost:5000/{image}.png
You can not access it from the local directory as you are saving the image using NodeJS.
If you are trying to access on local machine where your node server is also running then use
http://localhost:3000/server/public/upload/{image}
If you are trying to access the image from already deployed node application then use
http://abchost:3000/server/public/upload/{image}
I have HTML, CSS, and Javascript programs that work perfectly together. I've recently realized that I'm going to need a server to be able to complete some of my functionality. I've created a local Node server using some tutorials. After reading some suggestions, I'm trying to use Express to try to add the HTML, CSS, and Javascript to the Node, which are all in the same folder. The code I have (below) just causes the browser to stay on loading.
const http = require('http');
const fs = require('fs').promises;
const host = 'localhost';
const port = 8000;
var express = require('express');
var path = require('path');
var app = express();
const requestListener = function (req, res) {
app.use(express.static(path.join(__dirname, 'public')));
//res.writeHead(200);
//res.end("My first server!");
};
const server = http.createServer(requestListener);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
you don't need http module if you are using express...
const express = require('express')
const app = express()
// '/' is the url you want to host your site
// 'public' is the folder in which you have the necessary frontend files
// and the main html should be named as 'index.html' inside 'public'
app.use('/', express.static('public'))
app.listen(5000, () => console.log('server on port 5000'))
Try this....
const express = require('express');
const app = express();
const path = require('path');
app.use(express.static(path.join(__dirname,'css'));
app.use('/html',(req,res,next)=>{
res.sendFile(path.join(__dirname,'HTML','text.html');});
app.listen(3000);
I am attempting to deploy a Vue.js, Node, Express, MongoDB (MEVN) stack application to Netlify. I successfully deployed the front end of the application to Netlify, and am now attempting to deploy the express server, based on the following serverless-http example: https://github.com/neverendingqs/netlify-express/blob/master/express/server.js
I configured my server to include the serverless-http package:
server.js
const express = require('express');
const app = express();
const serverless = require('serverless-http');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const config = require('./DB.js');
const postRoute = require('./routes');
mongoose.connect(config.DB, { useNewUrlParser: true, useUnifiedTopology: true }).then(
() => { console.log('Database is connected') },
err => { console.log('Can not connect to the database'+ err)}
);
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/messages', postRoute);
app.use('/.netlify/functions/server', router); // path must route to lambda
app.use('/', (req, res) => res.sendFile(path.join(__dirname, '../public/index.html')));
module.exports = app;
module.exports.handler = serverless(app);
routes.js
const express = require('express');
const postRoutes = express.Router();
// Require Post model in our routes module
let Post = require('./post.model');
// Defined store route
postRoutes.route('/add').post(function (req, res) {
let post = new Post(req.body);
post.save()
.then(() => {
res.status(200).json({'business': 'business in added successfully'});
})
.catch(() => {
res.status(400).send("unable to save to database");
});
});
// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
Post.find(function(err, posts){
if(err){
res.json(err);
}
else {
res.json(posts);
}
});
});
module.exports = postRoutes;
I then re-deployed my application to Netlify, but the server does not seem to run in Netlify. This server is in a folder in project root of my vue.js app. Should I instead run the server as a separate site in Netlify? If not, what should I do in order to get the server to run when deployed in Netlify?
It's been a while, but here goes.
Netlify hosting is for the Jamstack, as they say, i.e. only static files, no processing on the server. The idea is to make use of other mechanisms to get your data dynamically, such as APIs hosted elsewhere, which you query straight from the browser, or when you build your site.
Most likely you actually had to deploy your express.js app as a Netlify Function, instead. Check Netlify's blog post on running express apps on their functions.
I had a similar issue, just that my server wouldn't connect to the routes locally, the major difference between my code and yours was that I had to do
const router = express.Router()
and then switched app.use() with router.use()
Like I said, that's for when the localhost says "cannot GET /* a defined path */"
P.S. As a side note, you don't need explicit bodyParser in recent express, express.json() works fine instead.
I have a Nuxt App, with one service which needs to be delivered over WebSockets. The Nuxt App Server provides an api service using express.
I have an /api folder in which there are various *.js files, and these are routed to successfully. ie...
const express = require('express');
const app = express();
app.get('/whatever1',(req, res) => console.log('req.url',req.url))
works OK.
However the following, in the same file, will never be reached....
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/whatever2',(ws,req) => {
console.log('req.url',req.url);
})
Where am I going wrong ?
You're attempting to connect the client to an endpoint on the server where no such endpoint exists. In your client's output, you're receiving an error of:
VM1295:1 WebSocket connection to 'ws://localhost:3000/api/whatever2' failed: Connection closed before receiving a handshake response
because you haven't defined a route of /api/whatever2. Your code above routes to:
ws://localhost:3000/whatever2
instead of ws://localhost:3000/api/whatever2
EDIT:
Here's test code that worked for me:
const express = require('express');
var app = express();
const expressWS = require('express-ws')(app);
expressWS.getWss().on('connection', function (ws) {
console.log('connection open');
});
app.ws('/whatever', (ws, res) => {
console.log('socket', ws);
});
app.listen(3000, () => console.log('listening on 3000...'));