Help Setting up frontend with the backend hosted on Railway

richardpinewoodHOBBY

4 months ago

Hey guys,i am building a project using html,css and javascript in the forntend, and in the server side nodejs, now i am facing a problem were i dont know how to connect the frontend with the new backend route ,since now it is being hosted on railway.

Solved

0 Replies

richardpinewoodHOBBY

4 months ago

N/A


richardpinewoodHOBBY

4 months ago

i can see the link up


richardpinewoodHOBBY

4 months ago

and i even tried to change the route in my frontend


richardpinewoodHOBBY

4 months ago

heres an example : ```const form = document.getElementById('loginForm');
const emailInput = document.getElementById('email');
const passwordInput = document.getElementById('password');

form.addEventListener('submit', async (e) => {
e.preventDefault();

const email = emailInput.value.trim();
const password = passwordInput.value.trim();

if (!email || !password) {
alert('Por favor preenche os campos em branco');
return;
}

const data = { email, password };

try {
const response = await fetch('https://zethirahd-production-c2af.up.railway.app/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});

const result = await response.json();

if (response.ok && result.token) {
  alert('Login feito com sucesso!');

  localStorage.setItem('token', result.token);

  window.location.href = '/home.html';
} else {
  alert(result.message || 'Erro no sistema!');
}

} catch (error) {
alert('Um erro ocorreu, tente novamente mais tarde');
console.error('Login error:', error);
}
});
```


4 months ago

any logs on the api?


4 months ago

I just tested a POST request to that address through my http client and it returned 404


richardpinewoodHOBBY

4 months ago

you mean in the backend ?


richardpinewoodHOBBY

4 months ago

i see this logs on railway : MongoDB connection error: MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.

at NativeConnection.createClient (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:225:11)

at NativeConnection.openUri (/app/node_modules/mongoose/lib/connection.js:1016:34)

at Mongoose.connect (/app/node_modules/mongoose/lib/mongoose.js:446:15)

at Object. (/app/server.js:18:4)

at Module._compile (node:internal/modules/cjs/loader:1364:14)

at Module._extensions..js (node:internal/modules/cjs/loader:1422:10)

at Module.load (node:internal/modules/cjs/loader:1203:32)

at Module._load (node:internal/modules/cjs/loader:1019:12)

at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12)

at node:internal/main/run_main_module:28:49

Error: ENOENT: no such file or directory, stat '/ZethiraHD/home.html'


4 months ago

the error is happening in your mongodb connection in your api


4 months ago

your api is prob crashing before even serving routes


richardpinewoodHOBBY

4 months ago

so the problem is with my database ?


4 months ago

yes, did u also deploy a database in railway?


richardpinewoodHOBBY

4 months ago

i did ,used mongodb


richardpinewoodHOBBY

4 months ago

1342564813070405600


4 months ago

nice, and how did u point your API to use that db?


4 months ago

if u used the private url from the DB railway would show a connection arrow between your API ---> MongoDB on the dashboard


4 months ago

but the error says it received a undefined URI


richardpinewoodHOBBY

4 months ago

i used a .env file to store the connections off my Mongodb databse….


4 months ago

did u manage to make it work @Richard Pinewood ?


richardpinewoodHOBBY

4 months ago

Not yet, i am going to see if i can solve the problem tomorrow!


4 months ago

ok


richardpinewoodHOBBY

4 months ago

it crashed 😭


richardpinewoodHOBBY

4 months ago

can anyone just guide me in simple terms ?


4 months ago

medim can't read minds yet, you need to tell him the specific errors


richardpinewoodHOBBY

4 months ago

i was able to setup it once,with a old project in the free tier


richardpinewoodHOBBY

4 months ago

now this project has more things


4 months ago

^


richardpinewoodHOBBY

4 months ago

for now it is appearing this : Mongo URI from .env: undefined

MONGO_URI is not defined. Check the .env file.


richardpinewoodHOBBY

4 months ago

in the logs


richardpinewoodHOBBY

4 months ago

i have installed dotenv


4 months ago

please do not use .env in a production environment


richardpinewoodHOBBY

4 months ago

```require("dotenv").config({ path: "./.env" });

const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const path = require("path");
const authRoutes = require("./routes/userRoutes");

const app = express();
const PORT = process.env.PORT || 5000;
const MONGOURI = process.env.MONGOURI;

console.log("Mongo URI from .env:", MONGO_URI);

if (!MONGOURI) { console.error(" MONGOURI is not defined. Check the .env file.");
process.exit(1);
}

app.use(cors());
app.use(express.json());

mongoose
.connect(MONGO_URI)
.then(() => console.log("Connected to MongoDB"))
.catch((err) => console.error("MongoDB connection error:", err));

app.use("/uploads", express.static(path.join(dirname, "uploads"))); app.use(express.static(path.join(dirname, "../frontend/build")));

app.use("/api/auth", authRoutes);

app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname, "../ZethiraHD/home.html"));
});

app.listen(PORT, () => console.log(Server running on port ${PORT})); ```


4 months ago

but I'll let medim take it from here


richardpinewoodHOBBY

4 months ago

why is it wrong ?


4 months ago

.env is for local development only


richardpinewoodHOBBY

4 months ago

i hided the file from github


richardpinewoodHOBBY

4 months ago

shouldnt be bcs of this ?


richardpinewoodHOBBY

4 months ago

or railway will crash bcs of it ?


4 months ago

railway has nothing to do with .env files


richardpinewoodHOBBY

4 months ago

but thats were i store the mongodb_url


4 months ago

^


richardpinewoodHOBBY

4 months ago

this is my repo just in case if anyone is intrested to understand the project : https://github.com/RichardPinewood/ZethiraHD


4 months ago

^


4 months ago

ok you don't seem to be commiting your .envwhich is good


4 months ago

but did you set the service variables in railway?


4 months ago

no .env file, but there are multiple node_modules folders 😦


4 months ago

ye


4 months ago

@Richard Pinewood are you setting the service variables? also gitignore your node_modules


richardpinewoodHOBBY

4 months ago

i didnt add any variables yet

1342852856276848600


richardpinewoodHOBBY

4 months ago

in my backend


richardpinewoodHOBBY

4 months ago

@Medim


richardpinewoodHOBBY

4 months ago

1342853475951837200


richardpinewoodHOBBY

4 months ago

what variable should i add ? the Mongo_URL ?


4 months ago

that's the issue


4 months ago

in your backend you use the MONGO_URI var


4 months ago

so you need to set it in the service variables


4 months ago

MONGO_URI=YOUR-MONGODB-URL


4 months ago

which you can use the reference variables from railway


4 months ago

the ones displayed here


4 months ago

so, the field VARIABLE_NAME would be MONGO_URI and the VALUE would be the reference to the mongodb url


4 months ago

1342855478396321800


4 months ago

could u try that @Richard Pinewood ?


richardpinewoodHOBBY

4 months ago

But do i need to put the real credentials?


richardpinewoodHOBBY

4 months ago

Like i did in the enviormental file?


4 months ago

yes


4 months ago

but in this case, you can use the reference variable just like I showed here


4 months ago

I mean, it needs to be the "real credential" otherwise how would it work? <:thonk:969365165688635464>


4 months ago

and by "real credential" I mean the mongodb one that is hosted on railway


4 months ago

could u try that @Richard Pinewood ?


richardpinewoodHOBBY

4 months ago

1342859896445472800


4 months ago

exactly.


4 months ago

just one issue


4 months ago

in your code you use MONGO_URI (with an i)


4 months ago

you wrote MONGO_URL (with a l)


4 months ago

just the variable name


4 months ago

the value is correct


richardpinewoodHOBBY

4 months ago

oh damn,i didnt noted that lmao


richardpinewoodHOBBY

4 months ago

lets see


richardpinewoodHOBBY

4 months ago

it still appears the same issue


4 months ago

^


richardpinewoodHOBBY

4 months ago

1342861281534808000


4 months ago

^


4 months ago

^


richardpinewoodHOBBY

4 months ago

wait,in the beggining should it be URI to ?


richardpinewoodHOBBY

4 months ago

were it is these {}

1342862241468514300


4 months ago

it needs to be exactly as this screenshot


richardpinewoodHOBBY

4 months ago

hmmmm


4 months ago

the first field should be MONGO_URI


richardpinewoodHOBBY

4 months ago

i will delet the variable and do it again


4 months ago

yours is MONGO_URL


4 months ago

the second one you shouldn't change, since it's a reference variable


4 months ago

that works.


richardpinewoodHOBBY

4 months ago

what if i change in the code ?


richardpinewoodHOBBY

4 months ago

to URL ?


4 months ago

then u would change the service variable name to MONGO_URL too.


4 months ago

to match what your code uses.


richardpinewoodHOBBY

4 months ago

do i need to add the "i" in the end ?


richardpinewoodHOBBY

4 months ago

i wrote this : ${{MongoDB.MONGO_URI}}


richardpinewoodHOBBY

4 months ago

yoo,the error dissapeared,now it is giving me a diffrent one funny


richardpinewoodHOBBY

4 months ago

```MongoDB connection error: MongoParseError: Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"

at new ConnectionString (/app/node_modules/mongodb-connection-string-url/lib/index.js:86:19)

at parseOptions (/app/node_modules/mongodb/lib/connection_string.js:185:17)

at new MongoClient (/app/node_modules/mongodb/lib/mongo_client.js:53:63)

at NativeConnection.createClient (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js:312:14)

at NativeConnection.openUri (/app/node_modules/mongoose/lib/connection.js:1016:34)

at Mongoose.connect (/app/node_modules/mongoose/lib/mongoose.js:446:15)

at Object. (/app/server.js:25:4)

at Module._compile (node:internal/modules/cjs/loader:1364:14)

at Module._extensions..js (node:internal/modules/cjs/loader:1422:10)

at Module.load (node:internal/modules/cjs/loader:1203:32)```

richardpinewoodHOBBY

4 months ago

let me see if i can fix this first


4 months ago

that is wrong


4 months ago

that var shouldn't be changed, that var is provided by the MongoDB database you deployed, I think you're confusing things up a bit.


4 months ago

but seems like you app finally recognized the env var


4 months ago

just the value of it is wrong, since you changed it


richardpinewoodHOBBY

4 months ago

i added the i later on before i checkmark the variable


4 months ago

what does your var looks like right now?


richardpinewoodHOBBY

4 months ago

1342867995252228400


richardpinewoodHOBBY

4 months ago

it looks like this


4 months ago

why is there an "i" at the end


4 months ago

you SHOULDN'T change the value field


4 months ago

1342868223573627000


richardpinewoodHOBBY

4 months ago

isnt this an i ?


4 months ago

.


richardpinewoodHOBBY

4 months ago

so i dont need to put an i at the end of the value ?


4 months ago

No, and you should never do that


richardpinewoodHOBBY

4 months ago

i mean you forgot remove it in your example lol


4 months ago

it should be ${{MongoDB.MONGO_URL}}


4 months ago

I didn't put it in my example


richardpinewoodHOBBY

4 months ago

but URL in my case is URI


4 months ago

I put it in the name


4 months ago

that doesn't matter.


4 months ago

just put it that way


4 months ago

and it should work flawlessly


4 months ago

just as I said in the first example I gave you


richardpinewoodHOBBY

4 months ago

1342869773783928800


richardpinewoodHOBBY

4 months ago

omg i feel so dumb ahaha


richardpinewoodHOBBY

4 months ago

but have a look


richardpinewoodHOBBY

4 months ago

now no red errors are appearing in the logs yeiii


richardpinewoodHOBBY

4 months ago

i think the back is working fine !


richardpinewoodHOBBY

4 months ago

now lets setup the frontend !


richardpinewoodHOBBY

4 months ago

i will use netlify for that


4 months ago

congrats, you made it work


4 months ago

remember to also set the rest of your vars


4 months ago

and also remember this help thread isn’t for coding help, this wasn’t a railway related issue.


4 months ago

railway docs also introduce you on how it works so you should also take a look at it


richardpinewoodHOBBY

4 months ago

the other variables like how many ?


4 months ago

?


4 months ago

that’s defined by you


4 months ago

did you use any other var in your project? any other process.env.var-here?


4 months ago

what did you have in your .env?


4 months ago

everything there can be a service var


richardpinewoodHOBBY

4 months ago

no,i just have a .evn file in the backend


richardpinewoodHOBBY

4 months ago

and in that enviromental i just stored the MONGO_URI,and the port


4 months ago

cool, so seems like you’re set.


richardpinewoodHOBBY

4 months ago

for the frontend part,i just need to call the link they provide us right ?


4 months ago

you will generate a domain in the backend service settings


4 months ago

and call that domain in your frontend


richardpinewoodHOBBY

4 months ago

damnn,its workingg !


richardpinewoodHOBBY

4 months ago

i dont even need to use my machine to run my web-apps !


4 months ago

cool! so can Brody close this thread now?


richardpinewoodHOBBY

4 months ago

i mean,yheaa


richardpinewoodHOBBY

4 months ago

its working fine now !


4 months ago

@Brody


4 months ago

!s


Status changed to Solved brody 4 months ago


Help Setting up frontend with the backend hosted on Railway - Railway Help Station