Communicate backend with frontend in railway

I have an app in railway that has 2 parts, the front and the backend (PHOTO 1) The backend tells me to use that to communicate internally (PHOTO 2) This is my code in frontend:
const handleSubmit = async (event) => {
event.preventDefault()

try {
const result = await axios.post(
'http://localhost:3001/auth/login',
{
username,
password,
}
)
console.log(result.status)

setCookie('access_token', result.data.token)
window.localStorage.setItem('token', result.data.token)
window.localStorage.setItem('userID', result.data.userID)
console.log(result.data.userID)
if (result.data.userID === undefined) {
logout()
alert('Acceso denegado')
} else {
navigate('/home')
}
} catch (error) {
console.error(error)
alert('Acceso denegado')
}
}
const handleSubmit = async (event) => {
event.preventDefault()

try {
const result = await axios.post(
'http://localhost:3001/auth/login',
{
username,
password,
}
)
console.log(result.status)

setCookie('access_token', result.data.token)
window.localStorage.setItem('token', result.data.token)
window.localStorage.setItem('userID', result.data.userID)
console.log(result.data.userID)
if (result.data.userID === undefined) {
logout()
alert('Acceso denegado')
} else {
navigate('/home')
}
} catch (error) {
console.error(error)
alert('Acceso denegado')
}
}
And this my backend :
router.post('/login', async(req,res) =>{
const { username,password } = req.body;
const user = await UserModel.findOne({ username });
console.log(req)
if (!user){
return res.json({ message: "user doesn't exist"});
}

const isPasswordValid = await bcrypt.compare(password,user.password);
if (!isPasswordValid){
return res.json({message: "user or password is incorrect"});
}

const token = jwt.sign({ id : user._id }, "secret");

res.json({ token, userID: user._id});

});
router.post('/login', async(req,res) =>{
const { username,password } = req.body;
const user = await UserModel.findOne({ username });
console.log(req)
if (!user){
return res.json({ message: "user doesn't exist"});
}

const isPasswordValid = await bcrypt.compare(password,user.password);
if (!isPasswordValid){
return res.json({message: "user or password is incorrect"});
}

const token = jwt.sign({ id : user._id }, "secret");

res.json({ token, userID: user._id});

});
and this is my index.js from my backend , its runs by a nodemon
31 Replies
Percy
Percy16mo ago
Project ID: N/A
Alejandro Capra
Alejandro CapraOP16mo ago
import express from "express";
import moongose from "mongoose";

import { userRouter } from "./routes/user.js";
import { modelsRouter } from "./routes/models.js";
import { tokenRouter } from "./routes/token.js";

const app = express();

app.use(express.json());


app.use("/auth", userRouter);
app.use("/models", modelsRouter);
app.use("/forge", tokenRouter);

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

moongose.connect(
"mongodb+srv://user:[email protected]",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);

app.listen(3001, () => console.log("Server started at port 3001"));
import express from "express";
import moongose from "mongoose";

import { userRouter } from "./routes/user.js";
import { modelsRouter } from "./routes/models.js";
import { tokenRouter } from "./routes/token.js";

const app = express();

app.use(express.json());


app.use("/auth", userRouter);
app.use("/models", modelsRouter);
app.use("/forge", tokenRouter);

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});

moongose.connect(
"mongodb+srv://user:[email protected]",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);

app.listen(3001, () => console.log("Server started at port 3001"));
What do I have to use to communicate with the backend from the front? I try with: 'http://backend.railway.internal:3001/auth/login', 'https://backend.railway.internal:3001/auth/login', 'http://backend.railway.internal/auth/login', 'http://backend/auth/login', 'https://backend/auth/login', 'backend/auth/login', And nothing, what am I doing wrong? Project ID: 99233283-dda8-4de0-8f5e-52189f3955db
Brody
Brody16mo ago
this is a CSR frontend app?
Alejandro Capra
Alejandro CapraOP16mo ago
A mern app , backend in node.js with connection to a mongodb atlas , frontend in react Note i use CI=false npm run build to build the frontend because yarn run build give erros because axios Sorry, I don't have that much knowledge if it is crs.
Brody
Brody16mo ago
sorry, i dont know why i used an acronym, csr is client side rendered, is that the type of app your frontend is?
Alejandro Capra
Alejandro CapraOP16mo ago
I was researching and it uses CSR because react use ReactDOM
Brody
Brody16mo ago
sounds good, then you need to call a public backend domain, to get that head to the backend's service settings and click generate
Alejandro Capra
Alejandro CapraOP16mo ago
i generate a public domain in my backend to test
Alejandro Capra
Alejandro CapraOP16mo ago
in my login page , i write >
const handleSubmit = async (event) => {
event.preventDefault()

try {
const result = await axios.post(
'https://testforbrody.up.railway.app:3001/auth/login',
{
username,
password,
}
)
console.log(result.status)
const handleSubmit = async (event) => {
event.preventDefault()

try {
const result = await axios.post(
'https://testforbrody.up.railway.app:3001/auth/login',
{
username,
password,
}
)
console.log(result.status)
Brody
Brody16mo ago
why as a test? give it a proper name
Alejandro Capra
Alejandro CapraOP16mo ago
to test jaja I was fighting all day with 500 tests haha its okey?
Brody
Brody16mo ago
do not specify a port, you can only access your app over 443
Alejandro Capra
Alejandro CapraOP16mo ago
ah thats good to know in my backend the app have to listen 443 port?
Brody
Brody16mo ago
and since you are using the https scheme, you also dont need to specify 443, since thats implied when using https nope, your backend app needs to listen to process.env.PORT please read this https://docs.railway.app/troubleshoot/fixing-common-errors
Alejandro Capra
Alejandro CapraOP16mo ago
A lots of thanks brody u help me a lot
Brody
Brody16mo ago
side note, can you send me your package.json for your frontend app?
Alejandro Capra
Alejandro CapraOP16mo ago
nobleza obliga
"dependencies": {
"@ant-design/charts": "^1.4.2",
"@ant-design/icons": "^5.2.5",
"@googlemaps/google-maps-services-js": "^3.3.35",
"@headlessui/react": "^1.7.16",
"@heroicons/react": "^2.0.18",
"@react-google-maps/api": "^2.19.2",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"antd": "^5.8.2",
"axios": "^1.4.0",
"babel-plugin-react-html-attrs": "^3.0.5",
"chart.js": "^4.3.3",
"chartjs-plugin-datalabels": "^2.2.0",
"d3-interpolate": "^3.0.1",
"lodash": "^4.17.20",
"pannellum-react": "^1.2.4",
"react": "^18.2.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
"react-google-maps": "^9.4.5",
"react-google-places-autocomplete": "^4.0.1",
"react-places-autocomplete": "^7.3.0",
"react-router": "^6.14.2",
"react-router-dom": "^6.14.2",
"react-scripts": "^5.0.1",
"tailwindcss": "^3.3.3",
"web-vitals": "^3.4.0"
},
"dependencies": {
"@ant-design/charts": "^1.4.2",
"@ant-design/icons": "^5.2.5",
"@googlemaps/google-maps-services-js": "^3.3.35",
"@headlessui/react": "^1.7.16",
"@heroicons/react": "^2.0.18",
"@react-google-maps/api": "^2.19.2",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"antd": "^5.8.2",
"axios": "^1.4.0",
"babel-plugin-react-html-attrs": "^3.0.5",
"chart.js": "^4.3.3",
"chartjs-plugin-datalabels": "^2.2.0",
"d3-interpolate": "^3.0.1",
"lodash": "^4.17.20",
"pannellum-react": "^1.2.4",
"react": "^18.2.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
"react-google-maps": "^9.4.5",
"react-google-places-autocomplete": "^4.0.1",
"react-places-autocomplete": "^7.3.0",
"react-router": "^6.14.2",
"react-router-dom": "^6.14.2",
"react-scripts": "^5.0.1",
"tailwindcss": "^3.3.3",
"web-vitals": "^3.4.0"
},
Brody
Brody16mo ago
is that your full frontend package.json
Alejandro Capra
Alejandro CapraOP16mo ago
yes
Brody
Brody16mo ago
where the start script
Alejandro Capra
Alejandro CapraOP16mo ago
sorry
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@ant-design/charts": "^1.4.2",
"@ant-design/icons": "^5.2.5",
"@googlemaps/google-maps-services-js": "^3.3.35",
"@headlessui/react": "^1.7.16",
"@heroicons/react": "^2.0.18",
"@react-google-maps/api": "^2.19.2",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"antd": "^5.8.2",
"axios": "^1.4.0",
"babel-plugin-react-html-attrs": "^3.0.5",
"chart.js": "^4.3.3",
"chartjs-plugin-datalabels": "^2.2.0",
"d3-interpolate": "^3.0.1",
"lodash": "^4.17.20",
"pannellum-react": "^1.2.4",
"react": "^18.2.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
"react-google-maps": "^9.4.5",
"react-google-places-autocomplete": "^4.0.1",
"react-places-autocomplete": "^7.3.0",
"react-router": "^6.14.2",
"react-router-dom": "^6.14.2",
"react-scripts": "^5.0.1",
"tailwindcss": "^3.3.3",
"web-vitals": "^3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"prettier": {
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
},
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11"
}
}
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@ant-design/charts": "^1.4.2",
"@ant-design/icons": "^5.2.5",
"@googlemaps/google-maps-services-js": "^3.3.35",
"@headlessui/react": "^1.7.16",
"@heroicons/react": "^2.0.18",
"@react-google-maps/api": "^2.19.2",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"antd": "^5.8.2",
"axios": "^1.4.0",
"babel-plugin-react-html-attrs": "^3.0.5",
"chart.js": "^4.3.3",
"chartjs-plugin-datalabels": "^2.2.0",
"d3-interpolate": "^3.0.1",
"lodash": "^4.17.20",
"pannellum-react": "^1.2.4",
"react": "^18.2.0",
"react-cookie": "^4.1.1",
"react-dom": "^18.2.0",
"react-google-maps": "^9.4.5",
"react-google-places-autocomplete": "^4.0.1",
"react-places-autocomplete": "^7.3.0",
"react-router": "^6.14.2",
"react-router-dom": "^6.14.2",
"react-scripts": "^5.0.1",
"tailwindcss": "^3.3.3",
"web-vitals": "^3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"prettier": {
"trailingComma": "es5",
"tabWidth": 4,
"semi": false,
"singleQuote": true
},
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11"
}
}
Alejandro Capra
Alejandro CapraOP16mo ago
i will , and another question , if my post in the frontend is
const handleSubmit = async (event) => {
event.preventDefault()

try {
const result = await axios.post(
'https://testforbrody.up.railway.app/auth/login',
{
username,
password,
}
)
console.log(result.status)
const handleSubmit = async (event) => {
event.preventDefault()

try {
const result = await axios.post(
'https://testforbrody.up.railway.app/auth/login',
{
username,
password,
}
)
console.log(result.status)
and i restructure my index.js in the backend to this >
import express from "express";
import mongoose from "mongoose";
import { userRouter } from "./routes/user.js";
import { modelsRouter } from "./routes/models.js";
import { tokenRouter } from "./routes/token.js";

const app = express();
app.use(express.json());
app.use("/auth", userRouter);
app.use("/models", modelsRouter);
app.use("/forge", tokenRouter);

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
mongoose.connect(
"mongodb+srv://[email protected]",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
// Use PORT provided in environment or default to 3001
const port = process.env.PORT || 3001;
// Listen on `port` and 0.0.0.0
app.listen(port, "0.0.0.0", () => {
console.log(`Server started at port ${port}`);
});
import express from "express";
import mongoose from "mongoose";
import { userRouter } from "./routes/user.js";
import { modelsRouter } from "./routes/models.js";
import { tokenRouter } from "./routes/token.js";

const app = express();
app.use(express.json());
app.use("/auth", userRouter);
app.use("/models", modelsRouter);
app.use("/forge", tokenRouter);

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
mongoose.connect(
"mongodb+srv://[email protected]",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
// Use PORT provided in environment or default to 3001
const port = process.env.PORT || 3001;
// Listen on `port` and 0.0.0.0
app.listen(port, "0.0.0.0", () => {
console.log(`Server started at port ${port}`);
});
I can use port 3001 with the variable in railway?
Brody
Brody16mo ago
ah sorry i should have mentioned that, my bad you do not need to (and should not) set a PORT in the service variables when your app listens on PORT as railway generates one for you automatically
Alejandro Capra
Alejandro CapraOP16mo ago
So this line // Use PORT provided in environment or default to 3001 const port = process.env.PORT || 3001; to // Use PORT provided in environment or default to railway decided const port = process.env.PORT; right?
Brody
Brody16mo ago
nope, what you had was correct, no need to change that please read my message again
alexdiz88
alexdiz8816mo ago
How did you configure the allowed IP addresses in MongoDB Atlas? Did you choose 'allow all' or did you specify a specific IP address range for Railway?
Alejandro Capra
Alejandro CapraOP16mo ago
allow all , @Brody again me jaja , how i could find the ip from railway to whitelist in mongo?
Brody
Brody16mo ago
you would need to allow all, as deployments on railway have dynamic ips, and you could end up with any one of the thousands of ips for the region but anyway, did you get your frontend and backend working? you never follow up?
Alejandro Capra
Alejandro CapraOP16mo ago
Hi , thnk for the aswer , its already working
Brody
Brody16mo ago
perfect!
Want results from more Discord servers?
Add your server