9 months ago
Hello!
I have a problem with create public networking
With "Access your application over HTTP with the following domains"
Service give me this adress
task04production.up.railway.app
Port 5000
But if i useit or just go for this i have error
Cannot GET /
Please help with it, how i can fix that.
6 Replies
9 months ago
It's completely normal for the root path of an API to not have a handler.
What is your actual issue?
9 months ago
I have another deploy on Vercel
https://task-04-wine.vercel.app/login
It's connected with DB and Node in the project
But if i start login or register i take " https://task04production.up.railway.app/api/auth/login 404 (Not Found)"
or
"https://task04production.up.railway.app/api/auth/register 404 (Not Found)"
9 months ago
This would either be a config or an application level issue.
We would need a minimal reproducible example to be able to help here.
9 months ago
Okey!
This how i use in login.js
const apiUrl = "https://task04production.up.railway.app";
const Login = () => {
const handleLogin = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`${apiUrl}/api/auth/login`, {
email,
password,
});
This how i use in registration form
const apiUrl = "https://task04production.up.railway.app";
const handleRegister = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`${apiUrl}/api/auth/register`, {
email,
password,
});
This is my authService.js
(full code)
import axios from "axios";
const apiUrl = "https://task04production.up.railway.app";
export const register = async (email, password) => {
try {
const response = await axios.post(`${apiUrl}/register`, {
email,
password,
});
return response.data;
} catch (error) {
throw new Error(error.response?.data?.message || "Registration failed");
}
};
export const login = async (credentials) => {
try {
const response = await axios.post(`${apiUrl}/api/auth/login`, credentials);
const token = response.data.token;
localStorage.setItem("token", token);
return response.data;
} catch (error) {
throw new Error("Login failed");
}
};
export const isAuthenticated = async () => {
const token = localStorage.getItem("token");
if (!token) return false;
try {
const response = await axios.get(`${apiUrl}/api/auth/check-auth`, {
headers: { Authorization: `Bearer ${token}` },
withCredentials: true,
});
if (response.data.isAuthenticated) {
return true;
} else {
localStorage.removeItem("token");
return false;
}
} catch (error) {
if (error.response?.status === 403 || error.response?.status === 401) {
localStorage.removeItem("token");
}
return false;
}
};
export const logout = async () => {
try {
await axios.post(`${apiUrl}/logout`, {}, { withCredentials: true });
localStorage.removeItem("token");
} catch (error) {
throw new Error(error.response?.data?.message || "Logout failed");
}
};
9 months ago
Now i find more correctly issue
When i try to send POST with Insomnia a have 500
https://task04production.up.railway.app/api/auth/register
{
"email": "test@example.com",
"password": "yourpassword"
}
{
"message": "Server error"
}
This my server.js
const express = require("express");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const mysql = require("mysql2/promise");
const authRoutes = require("./routes/auth");
const userRoutes = require("./routes/users");
const adminRoutes = require("./routes/adminRoutes");
dotenv.config();
const app = express();
const allowedOrigins = [
process.env.CLIENT_ORIGIN,
"https://task-04-wine.vercel.app",
];
app.use((req, res, next) => {
const origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, X-Requested-With"
);
res.setHeader("Access-Control-Allow-Credentials", "true");
if (req.method === "OPTIONS") {
return res.sendStatus(200);
}
next();
});
app.use(cookieParser());
app.use(express.json());
app.use("/api/auth", authRoutes);
app.use("/api", userRoutes);
app.use("/api/admin", adminRoutes);
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: parseInt(process.env.DB_PORT, 10) || 3306,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
connectTimeout: 60000,
});
async function testDatabaseConnection() {
try {
const [rows] = await pool.query("SELECT 1 AS test_query");
console.log("Database test query result:", rows);
} catch (err) {
console.error("Error executing test query:", err.message);
}
}
async function initializeServer() {
try {
const connection = await pool.getConnection();
console.log("Connected to the MySQL database");
await testDatabaseConnection();
app.listen(process.env.PORT || 5000, () => {
console.log(`Server running on port ${process.env.PORT || 5000}`);
});
} catch (err) {
console.error("Error connecting to the database:", err.message);
process.exit(1);
}
}
initializeServer();
app.use((err, req, res, next) => {
console.error("Unexpected error:", err);
res.status(500).json({ message: "Internal Server Error" });
});
app.use("/api/auth", (req, res, next) => {
res.on("finish", () => {
console.log(
`Request to ${req.url} completed with status ${res.statusCode}`
);
});
next();
});
thhis how i use Route to /register
router.post("/register", async (req, res) => {
const { email, password } = req.body;
try {
const [users] = await db.query("SELECT * FROM users WHERE email = ?", [
email,
]);
if (users.length > 0) {
return res.status(400).json({ message: "User already exists" });
}
const hashedPassword = await bcrypt.hash(password, 10);
const result = await db.query(
"INSERT INTO users (email, password, token) VALUES (?, ?, ?)",
[email, hashedPassword, null]
);
const userId = result[0].insertId;
const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
expiresIn: "1h",
});
await db.query("UPDATE users SET token = ? WHERE id = ?", [token, userId]);
res.status(201).json({ message: "User registered successfully", token });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Server error" });
}
});
9 months ago
I'm sorry but a bunch of code blocks is a not a minimal reproducible example, you would need to provide a deploy-able repo.
Please read this - https://stackoverflow.com/help/minimal-reproducible-example