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.
0 Replies
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
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
4 months ago
yes, did u also deploy a database in railway?
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
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 ?
4 months ago
ok
4 months ago
medim can't read minds yet, you need to tell him the specific errors
4 months ago
^
for now it is appearing this : Mongo URI from .env: undefined
MONGO_URI is not defined. Check the .env file.
4 months ago
please do not use .env in a production environment
```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
4 months ago
.env is for local development only
4 months ago
railway has nothing to do with .env files
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 .env
which 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
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
4 months ago
could u try that @Richard Pinewood ?
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 ?
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
4 months ago
^
4 months ago
^
4 months ago
^
4 months ago
it needs to be exactly as this screenshot
4 months ago
the first field should be MONGO_URI
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.
4 months ago
then u would change the service variable name to MONGO_URL too.
4 months ago
to match what your code uses.
```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)```
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
4 months ago
what does your var looks like right now?
4 months ago
why is there an "i" at the end
4 months ago
you SHOULDN'T change the value field
4 months ago
4 months ago
.
4 months ago
No, and you should never do that
4 months ago
it should be ${{MongoDB.MONGO_URL}}
4 months ago
I didn't put it in my example
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
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
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
4 months ago
cool, so seems like you’re set.
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
4 months ago
cool! so can Brody close this thread now?
4 months ago
@Brody
4 months ago
!s
Status changed to Solved brody • 4 months ago