I am working on my nextjs project under docker, and when using getStaticProps my backend api is not available(which is also under docker). So I connected frontend to backend via networks and if i hardcode api for ssr request it works. But when i try to utilize serverRuntimeConfig and publicRuntimeConfig so i could switch between them depending on where code is being ran I get {} for serverRuntimeConfig. However publicRuntimeConfig is fine and i can access api from it.
My next.config.js is:
module.exports = {
publicRuntimeConfig: {
// Will be available on both server and client
baseUrl: 'http://localhost/api/v1',
},
serverRuntimeConfig: {
// Will only be available on the server side
baseUrl: 'http://backend_nginx_1/api/v1/',
},
am I missing something ?
This will sound dumb, but I spent 2 hours seeing the empty file been recognized by the system and just seeing {}.
Now... restarting the server, gives you access to the content of the file.
That was my solution.
And it was not included in the documentation.
https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration
Related
I put my frontend application in the public folder for a node.js application and am getting the form-data using the following request:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
My backend is in port 5000 and it's handling the request by:
app.use("/api/v1/contact-form", submitFormRouter);
It works perfect. I'm getting the data when I have my frontend application is in the node.js public folder.
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I replace the following path for post:
Frontend:
try {
await axios.post("/api/v1/contact-form", {
name,
email,
msg,
});
}
Backend:
app.use("/api/v1/contact-form", submitFormRouter)
I've also tried the code using React in which case the frontend is running in http://localhost:3000/ and node.js server running in 5000, the code still works and I'm getting the form data. But, how do I make it work for a frontend application sitting in a different port(without react)?
Additionally, I hope you're kind enough to answer the following question- What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?
What would be the path once I have the frontend let's say on Netlify whereas the backend is on Heroku?
Let's assume your Back on Heroku has this url https://app.herokuapp.com/ and the Front on Netlify this one https://app.netlify.com/. All you have to do is to give your Front your Back's url, like so:
try {
await axios.post("https://app.herokuapp.com/api/v1/contact-form", {
name,
email,
msg,
});
}
My question is if my frontend is running on a different local port such as, if I use "Five server" to run the frontend application, how do I...
At this point you have two choices, the simplest one is to use a complete url like above. Let's assume your Front is on port 3000 and the Back on 8080. All you have to do again is:
try {
await axios.post("http://localhost:8080/api/v1/contact-form", {
name,
email,
msg,
});
}
The second one is to use a proxy, and this really depends on your projects' structure and need.
I'm trying to set up a reverse proxy on the development server for my VUE js webapp to get around the CORS issue that I was getting when I was trying to use my flask HTTP APIs with the vue js webapp.
I did this by creating a vue.config.js file in the root of the project directory:
module.exports = {
devServer: {
proxy: 'http://localhost:5001/'
}
}
when I run npm run serve, and try to use a REST API defined on port 5001 - I don't see the request going to port 5001, it uses the same port as the web app.
And there are no useful logs being written to stdout either to help me debug this.
Has anyone come across this issue before ?
I had a similar issue and found that the port was already in use by another application and hence it was not going to the correct port. Once i shutdown the other app, it started working as expected.
I am struggling currently when making a call using Axios to my backend, I currently have a user register page and I want to send the user data to the backend, everything seems to be set up correctly but I get these errors inside of my google chrome.
Here is the code from my React Register.js that breaks my program and causes this error.
onSubmit(e) {
e.preventDefault();
const newUser = {
name: this.state.name,
email: this.state.email,
password: this.state.password,
password2: this.state.password2
};
axios.post('api/users/register', newUser) //EDIT : Line 35, where the error is
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
The onSubmit is connected to a button at the bottom of the website and all the code there is %100 fine. One issue that might be hurting me here is that my server is on localhost5000 while my front end is running on localhost3000 on my computer. I don't know how to fix this or what to do next, I've looked everywhere and this small issue is incredibyly frustrating.
Any help , pointers or general advice would be greatly appreciated as this seems like an extremely trivial error. Thanks in advance for any help.
Also look into the create-react-app docs to setup a proxy. CRA Proxy Docs
I like to setup my proxies in package.json (for the react client). I usually add the following, and all my routes start with api, to save on typing.
// somewhere in package.json
"proxy": {
"/api/*": {
"target": "http://localhost:5000"
}
}
If I was still getting a CORS error I would install the npm package cors (on the express app) and set that up as a middleware before my route handlers. Cors Docs
const app = express()
app.use(cors())
That is the most basic config, but you can specifically whitelist your front end if you want to.
app.use(cors({ origin: 'http://localhost:3000' }))
You can also add cors to any one route if you want to, in the usual express manner.
app.post('/api/user/register', cors(), (req,res) => {
// route handler
})
This is how I setup my apps using CRA and Express for development. Then when things go to production I don't have to change the api routes on the front end. That is the inherent problem with writing out the whole path ei: 'http://localhost:5000/api/users/register' - that is not going to work when the app goes to production say on Heroku, or wherever, and localhost:5000 is no longer the backend url. You would have to go back to all api routes and adjust them or insert ternaries for process.env.NODE_ENV, which is more work.
In this case all you need on the front end is axios.post('/api/users/register', newUser)
The proxy will take care of the rest in development.
Now when you publish site, if you chose to make it one single express app that serves your build statically, you just put the api route handlers above a catch all for serving the index.html. Anyways, this is a little beyond your question, just trying to give you an idea of one approach that will work down the line a little easier.
The issue is that when you run axios.post('api/users/register', newUser) it is running simply against http://localhost. You stated that the backend is running at http://localhost:5000 so you would want to run an absolute address to hit the backend properly. The code would turn into axios.post('http://localhost:5000/api/users/register', newUser) to hit the backend APIs.
Make sure you have "proxy": "http://localhost:5000" in your Client/React Package.json
I'm developing a React web app and I'm using the create-react-app npm utility.
My app communicates with a server which, during development, is on my local machine. For this reason all the Ajax request I make use a localhost:port address.
Of course, when I'm going to build and deploy my project in production I need those addresses to change to the production ones.
I am used to the preprocess Grunt plugin flow (https://github.com/jsoverson/grunt-preprocess) which has the possibility to mark parts of code to be excluded, included or changed at build time.
For example:
//#if DEV
const SERVER_PATH = "localhost:8888";
//#endif
//#if !DEV
const SERVER_PATH = "prot://example.com:8888";
//#endif
Do you know if there is a way to do such thing inside the create-react-app development environment?
Thank you in advance!
I'm not too sure exactly how your server-side code handles requests, however you shouldn't have to change your code when deploying to production if you use relative paths in your ajax queries. For example, here's an ajax query that uses a relative path:
$.ajax({
url: "something/getthing/",
dataType: 'json',
success: function ( data ) {
//do a thing
}
});
Hopefully that helps :)
When creating your networkInterface, use the process.env.NODE_ENV to determine what PATH to use.
if (process.env.NODE_ENV !== 'production') {
const SERVER_PATH = "localhost:8888";
}
else {
const SERVER_PATH = "prot://example.com:8888";
}
Your application will automatically detect whether you are in production or development and therefore create the const SERVER_PATH with the correct value for the environment.
According to the docs, the dev server can proxy your requests. You can configure it in your package.json like this:
"proxy": "http://localhost:4000",
Another option is to ask the browser for the current location. It works well when your API and static files are on the same backend, which is common with Node.js and React.
Here you go:
const { protocol, host } = window.location
const endpoint = protocol + host
// fetch(endpoint)
I started a project with my raspberry pi running an electron App where I need to get the actual weather from an open weather API. I am totally new to electron and not that experienced in Javascript. So I am stuck with getting the Data from the weather API into the App. I can request the Data as JSON or XML data. I tried out different ways I thought it might work but they all failed. So could someone tell me how to get API Data into electron in general?
The easiest way to start with API requests is to use axios.
After setting up the project (you can follow Getting Started), follow these steps:
Install Axios npm install --save axios
Create main.js in your project's folder.
Load main.js inside index.html somewhere before </body>.
Put the JavaScript code inside main.js
const axios = require('axios');
function fetchData() {
// you might need the next line, depending on your API provider.
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.post('api.example.com', {/* here you can pass any parameters you want */})
.then((response) => {
// Here you can handle the API response
// Maybe you want to add to your HTML via JavaScript?
console.log(response);
})
.catch((error) => {
console.error(error);
});
}
// call the function to start executing it when the page loads inside Electron.
fetchData();