Hello I need to run a function on first start of the server, basically I want to put some constant data in the database. Yes, I could use just a in memory constant for this but I'd rather have it in my database because I am planning on using that data on some of my other servers in the future. The problem is, I am using NextJS and I want to host on the Vercel platform so I don't want to use a custom server.js file.
Is there any way to run a function only once when the server first starts in NextJS/NodeJS?
So the Vercel platform is serverless: https://vercel.com/docs/serverless-functions/introduction.
As it states in the documentation you can create a serverless function like so:
module.exports = (req, res) => {
res.send("Hello World");
}
If you wish to run a function after the build is done you can look at this answer:
Next.js run function/script when starting app
You could also use getServerSideProps to run code before the page renders (on the server side) if that is what you mean with "app start".
https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
Related
Here is my HTML code in index.html.
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="stuff()">Click</button>
<script>
async function stuff() {
await connectToServer();
}
async function connectToServer() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(this.responseText);
};
xhttp.open('GET', 'C:/Users/myName/myFolder/index.js', true);
xhttp.send();
return;
}
</script>
</body>
</html>
Then, here is my backend code in index.js.
const express = require('express');
const axios = require('axios');
const port = process.env.PORT || 8080;
const app = express();
app.get('/', (req, res) => {
res.sendFile('C:/Users/myName/myFolder/views/index.html');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
I can type node index.js on the command line and run this program and go to http://localhost:8080/ . When I do this, the html page shows up as intended. However, when I click the button in order to make a GET request to the server side, I get a console error saying Not allowed to load local resource: file:///C:/Users/myName/myFolder/index.js . I'm using Google Chrome by the way.
I know that it is a security thing, and that you are supposed to make requests to files that are on a web server (they begin with http or https). I suppose then, my question is:
How do I make it so that my server file index.js can be viewed as being on a server so that I can call functions on the backend from my frontend?
You have to make an HTTP request to a URL provided by the server.
The only URL your server provides is http://localhost:8080/ (because you are running an HTTP server on localhost, have configured it to run on port 8080, and have app.get('/', ...) providing the only path.
If you want to support other URLs, then register them in a similar way and write a route to handle them.
The express documentation will probably be useful.
You should not need to load your server-side code into the browser. It's server-side code. It runs on the server. It isn't client-side code. It doesn't run in the browser. The browser does not need access to it.
If you want to load some actual client-side JS from the server, then use <script src="url/to/js"></script> (and not Ajax) and configure express' static middleware.
Let's improve your current flow by separating your backend API process from frontend hosting process. While backend can, it's not good in serving static html files (especially for local development purposes).
Run your backend as usual, node index.js. But as soon as this command will become more complicated, you will probably want to use npm scripts and do just npm start)
Run separate server process for frontend. Check out parcel, snowpack, DevServer. It can be as easy as npx parcel index.html, but this command is likely to change frequently with your understanding of your tool features.
To call backend, just add an API endpoint to an express app (just like you already did for serving static content), and call it, using backend process URL.
Usually, you will see your app on http://localhost/ and it should do requests to http://localhost:8080/.
If for some strange reason you will want to dynamically download js file from your server to execute it, you just need to serve this file from your frontend hosting process. In order to do so, different development servers have different techniques, but usually you just specify file extensions and paths you want to be available.
After editing frontend files, you will see hot-reload in browser. You can achieve the same for node process with various tools (start googling from nodemon)
If you find this way of operating not ideal, try to improve it, and check what people already did in this direction. For example, you can run two processes in parallel with concurrently.
In my React and node application, the is microservice architecture on the server side which is written in node.js, all the microservices are running different ports like
http://localhost:3001,
http://localhost:3002
so on..,
I want to point all the services in a single port so that I can consume that services in react through only one single URL as a base path.
want to do this on a local server/ local system.
As I want to run the application end to end on the local server.
Try to use an API GATEWAY with a Message Broker (rabbitmq for example) and in your service in index.js just consume the Queue of message broker. before send the response to the msg broker and This message are consume by your gateway
do you perhaps mean something like this?
you put this into the .env file
CONNECTION_URL = 'put your db url '
SECRET=...
BASE_URL='http://localhost:3000/'
NODE_ENV=env
as for front you can just call your functions by link
example
const getItem= () => {
Axios.get("http://localhost:5000/Items").then((response) => {
setListItem(response.data);
});
};
Using Nginx on WSL with Node.js resolved my issue, by creating a proxy server.
I`d like to show in my React application the running port of the local server, is there any way to get it programmatically? The running port may defer if something is already running on the default port of create-react-app.
create-react-app is a React toolchain, which packages some useful tools together to let you dive into development without any initial setup. Local development server is a part of that toolchain, it's only purpose is to serve static files your react app needs.
Sure, create-react-app lets you configure some options with environment variables but it is not meant to serve as backend for your react application.
You can achieve this with your own backend by writing an endpoint to get the server port but for the local server I don't think it is possible.
This functionality is not available since React App and Local server are running independently.
However, your server port will be available when you start the server. So you can have another API that will simply fetch the port of the server and that can be displayed accordingly.
Something like this on the server.
app.get('/server/port', (req, res) => {
return res.json({port: server.address().port})
})
where your server is started at
const server = app.listen(20000)
In the react app, you can have the fetch request like this
fetch('http://localhost:20000/server/port')
.then(response => response.json())
.then(data => console.log(data));
// you will have the port no. in data.port
This will be helpful to you.
I am trying to learn how to use Node.js and web sockets to create simple multi-user interactive javascript programs. I used this tutorial series by Daniel Shiffman to create this example project. My next step would be to upload it, using WinSCP, to my RaspberryPi apache2 web server, but I haven't found a way to edit the code in a way to allow for that to work, and furthermore, I do not know what piece of the programs to execute to make it function properly.
Any assistance would be great. The extent of my Node / Socket.io knowledge comes entirely from the video series mentioned above, so you can assume I know almost nothing else.
Apache is a web server and it serves your file and send them to client for you, so when you have some client side things like html site with some css, javascript and images you can use apache to send them to client for you.
In node.js you can create this web server simply by following code and express library:
// Create the app
var app = express();
// Set up the server
var server = app.listen(3000, () => {
console.log('http server is ready')
});
as you created in your code too. by this web server you can host your files and do many more things like setup socket.io server and ... because you write web server yourself. with following code you serve static files in public directory (html, css, javascript and images ...):
app.use(express.static('public'));
after you finishing this process you can run it simply by:
npm install
node server.js
if you want you can run you code inside docker by creating Dockerfile and ...
About your question, you must move all your project files into raspberry and at the end you have following directory tree in somewhere in raspberry:
|- server.js
|- package.json
\ public
at this directory run above commands and your server will be up and running and you can access to it by http://raspberry_ip:3000.
I have some data that I want to store locally and to be able to pull it dynamically, maybe in another session or after the browser was closed and all browser data was cleared.
I run the site with http-server CLI command and navigate to localhost to access it from the browser.
How can I send data to the server side so the server side will save the data as a file?
I tried to do an ajax post request to see if something happens in the console, but it just returned 404 and nothing came up in the console.
The docs don't mention anything about post requests: https://www.npmjs.com/package/http-server
PS: I have to run this with http-server, this is an offline project.
You will not be able to do this with http-server alone, because http-server can only serve static content and cannot be used to run any code on the server side.
You will have to write a backend yourself, possibly using a framework like Express, Hapi, Restify, Loopback etc. and serve your static files that you need with your new backend, or keep it served as you do now but then you will probably need to take CORS into account if you use different ports for your data saving/retrieving endpoints and your static content - unless you run a reverse proxy that makes it all appear on the same host name and port.
You can use the file system to save the data or you can use a database - either a standalone database like Mongo or Postgres or an embedded database like SQLite or Loki.
For examples on how to serve static content in your own backend see:
How to serve an image using nodejs
You should use express for this kind of stuff. You can easily make methods that handle certain requests.
Here is an exmaple on how to handle a get request by just sending some data
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
And you can use the fs api from node itself to write data.
var fs = require('fs')
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
Note: the fs example uses arrow functions. You can find more information here