One POST route worked, but another failed on remote server

In my express.js backend (connected to flutter frontend), I have two routes: POST /auth/registrasi and POST /auth/login.
If I run the backend on my localhost, both routes worked (I have tested it using Postman as well).

Strangely, when I deploy my backend to remote server and try to access both routes, POST /auth/login works just fine while POST /auth/registrasi makes my flutter screen show a message saying it can’t do the POST request.

Postman says my POST /auth/login returns 200 OK, while POST /auth/registrasi returns 404 NOT FOUND. But the thing is the /auth/registrasi returns 200 OK as well when I run it on localhost.

Here is my app.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import authRoutes from './routes/auth.routes.js'; // Importing routes
// import { dotenv } from 'dotenv';
import { populateDB, getUsernameById, getUserByUserName } from './databases/populate.postgre.js';
import { Sequelize } from 'sequelize';
import http from 'http';
import db from './databases/config.js';
import otpRoutes from './routes/otp.routes.js'; // Importing routes
import UserRoutes from './routes/user.routes.js'; // Importing routes
const app = express();
const PORT = 3001;
// Allow specific origin
const allowedOrigins = [
'http://localhost:', // Untuk web dari localhost
'http://http://10.0.2.2:', // Ganti dengan IP komputer host Anda
'http://http://192',
'http://http://196',
];
app.use(cors({
origin: '*',
methods: ['GET', 'POST'], // Allowed HTTP methods
credentials: true // Allow cookies and credentials
}));
app.use(bodyParser.json()); // Middleware to parse JSON requests
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
}
app.use(allowCrossDomain);
app.get('/', (req, res) => {
res.send('Welcome to the API!');
});
app.use('/auth', authRoutes); // Use authentication routes
app.use('/otp', otpRoutes); // Add OTP routes
app.use('/user', UserRoutes);
app.get('/populate', async (req, res) => {
await populateDB(); // Call the function to populate the database
res.send('Database populated!');
});
app.get('/user/:id', async (req, res, next) => {
const userId = parseInt(req.params.id, 10);
const [results] = await db.query(`
SELECT username, email
FROM users
WHERE id = ${userId};`);
// res.send(results[0].username);
res.send(results);
});
app.get('/username/:username', async (req, res, next) => {
// const userId = parseInt(req.params.id, 10);
const [ results ] = await db.query(`SELECT id FROM users WHERE username = '${req.params.username}'`);
// res.send(results[0].username);
res.send(results);
});
app.get('/cekOtp', async (req, res, next) => {
// const userId = parseInt(req.params.id, 10);
const [ result ] = await db.query(`
SELECT otp
FROM users
WHERE username = 'paksi4' AND email = '[email protected]';
`);
const tipe = typeof result[0].otp;
// res.send(results[0].username);
res.send(tipe);
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
</code>
<code>import express from 'express'; import bodyParser from 'body-parser'; import cors from 'cors'; import authRoutes from './routes/auth.routes.js'; // Importing routes // import { dotenv } from 'dotenv'; import { populateDB, getUsernameById, getUserByUserName } from './databases/populate.postgre.js'; import { Sequelize } from 'sequelize'; import http from 'http'; import db from './databases/config.js'; import otpRoutes from './routes/otp.routes.js'; // Importing routes import UserRoutes from './routes/user.routes.js'; // Importing routes const app = express(); const PORT = 3001; // Allow specific origin const allowedOrigins = [ 'http://localhost:', // Untuk web dari localhost 'http://http://10.0.2.2:', // Ganti dengan IP komputer host Anda 'http://http://192', 'http://http://196', ]; app.use(cors({ origin: '*', methods: ['GET', 'POST'], // Allowed HTTP methods credentials: true // Allow cookies and credentials })); app.use(bodyParser.json()); // Middleware to parse JSON requests var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); } app.use(allowCrossDomain); app.get('/', (req, res) => { res.send('Welcome to the API!'); }); app.use('/auth', authRoutes); // Use authentication routes app.use('/otp', otpRoutes); // Add OTP routes app.use('/user', UserRoutes); app.get('/populate', async (req, res) => { await populateDB(); // Call the function to populate the database res.send('Database populated!'); }); app.get('/user/:id', async (req, res, next) => { const userId = parseInt(req.params.id, 10); const [results] = await db.query(` SELECT username, email FROM users WHERE id = ${userId};`); // res.send(results[0].username); res.send(results); }); app.get('/username/:username', async (req, res, next) => { // const userId = parseInt(req.params.id, 10); const [ results ] = await db.query(`SELECT id FROM users WHERE username = '${req.params.username}'`); // res.send(results[0].username); res.send(results); }); app.get('/cekOtp', async (req, res, next) => { // const userId = parseInt(req.params.id, 10); const [ result ] = await db.query(` SELECT otp FROM users WHERE username = 'paksi4' AND email = '[email protected]'; `); const tipe = typeof result[0].otp; // res.send(results[0].username); res.send(tipe); }); app.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); }); </code>
import express from 'express';
import bodyParser from 'body-parser';
import cors from 'cors';
import authRoutes from './routes/auth.routes.js'; // Importing routes
// import { dotenv } from 'dotenv';
import { populateDB, getUsernameById, getUserByUserName } from './databases/populate.postgre.js';
import { Sequelize } from 'sequelize';
import http from 'http';
import db from './databases/config.js';
import otpRoutes from './routes/otp.routes.js'; // Importing routes
import UserRoutes from './routes/user.routes.js'; // Importing routes

const app = express();
const PORT = 3001;
// Allow specific origin
const allowedOrigins = [
  'http://localhost:', // Untuk web dari localhost
  'http://http://10.0.2.2:', // Ganti dengan IP komputer host Anda
  'http://http://192',
  'http://http://196',
];
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST'],   // Allowed HTTP methods
  credentials: true           // Allow cookies and credentials
}));
app.use(bodyParser.json()); // Middleware to parse JSON requests
var allowCrossDomain = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');

  next();
}
app.use(allowCrossDomain);

app.get('/', (req, res) => {
  res.send('Welcome to the API!');
});
app.use('/auth', authRoutes); // Use authentication routes
app.use('/otp', otpRoutes); // Add OTP routes
app.use('/user', UserRoutes); 
 
app.get('/populate', async (req, res) => {
  await populateDB(); // Call the function to populate the database
  res.send('Database populated!');
});
app.get('/user/:id', async (req, res, next) => {
  const userId = parseInt(req.params.id, 10);
  const [results] = await db.query(`
    SELECT username, email
      FROM users
      WHERE id = ${userId};`);
  // res.send(results[0].username);
  res.send(results);
});
app.get('/username/:username', async (req, res, next) => {
  // const userId = parseInt(req.params.id, 10);
  const [ results ] = await db.query(`SELECT id FROM users WHERE username = '${req.params.username}'`);

  // res.send(results[0].username);
  res.send(results);
});
app.get('/cekOtp', async (req, res, next) => {
  // const userId = parseInt(req.params.id, 10);
  const [ result ] = await db.query(`
    SELECT otp
      FROM users
      WHERE username = 'paksi4' AND email = '[email protected]';
  `);
  const tipe = typeof result[0].otp;
  // res.send(results[0].username);
  res.send(tipe);
});
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
}); 

Here is my auth.routes.js:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import dotenv from 'dotenv'; // Load environment variables from the .env file
import { Router } from 'express';
import { compare } from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getUserByUserName } from '../databases/populate.postgre.js';
import db from '../databases/config.js';
dotenv.config(); // Load environment variables
dotenv.config({ path: '.env.development.local' }); // Load environment variables
const { sign, verify } = jwt;
const router = Router();
const users = [
{
id: 1,
username: 'k1',
email: '[email protected]',
password: '$2a$12$zPlq1NLDZmgofBpy6LwiB.2q5zSU5TGQdk3Fh3Ll.PFYc7mrQXaAa' // bcrypt hash for 'ti3a'
}
];
const SECRET_KEY = process.env.JWT_SECRET_KEY;
router.post('/registrasi', async (req, res) => {
const { username, email, password } = req.body;
if (!username || !email || !password) {
return res.status(400).json({ error: 'Seluruh isian harus diisi' });
}
const [ checkUsername ] = await db.query(`SELECT id FROM users WHERE username = '${username}'`);
if (checkUsername.length > 0) {
return res.status(400).json({ error: 'Username sudah terdaftar' });
}
try {
await db.query(`
INSERT INTO users (username, email, password, status)
VALUES ('${username}', '${email}', '${password}','activated');
`);
res.status(200).json({ message: 'Registrasi berhasil', berhasil: true});
} catch (err) {
res.status(500).json({ error: `Kesalahan:n${err}` });
}
});
router.post('/login', async (req, res) => {
const { username, password } = req.body;
const [ userData ] = await db.query(`SELECT id, username, email, password FROM users WHERE username = "${username}" OR email = "${username}";`);
// Find user by username or email
const user = userData.find((user) => user['username'] === username || user['email'] === username);
if (!user) {
return res.status(401).json({ message: 'Username salah' });
}
// Check password
const isPasswordValid = await compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).json({ message: "password salah" });
}
// Create a JWT token
const token = sign({ id: user.id, username: user.username }, SECRET_KEY, {
expiresIn: '2h',
});
return res.status(200).json({ message: 'Login successful', token, id: user.id, username: user.username });
});
// Protected route
router.get('/protected', (req, res) => {
const token = req.headers['authorization'];
if (!token) {
return res.status(403).json({ message: 'No token provided' });
}
verify(token, SECRET_KEY, (err, decoded) => {
if (err) return res.status(401).json({ message: 'Failed to authenticate token' });
// Proceed with the request
return res.status(200).json({ message: 'Access granted', userId: decoded.id });
});
});
export default router;
</code>
<code>import dotenv from 'dotenv'; // Load environment variables from the .env file import { Router } from 'express'; import { compare } from 'bcrypt'; import jwt from 'jsonwebtoken'; import { getUserByUserName } from '../databases/populate.postgre.js'; import db from '../databases/config.js'; dotenv.config(); // Load environment variables dotenv.config({ path: '.env.development.local' }); // Load environment variables const { sign, verify } = jwt; const router = Router(); const users = [ { id: 1, username: 'k1', email: '[email protected]', password: '$2a$12$zPlq1NLDZmgofBpy6LwiB.2q5zSU5TGQdk3Fh3Ll.PFYc7mrQXaAa' // bcrypt hash for 'ti3a' } ]; const SECRET_KEY = process.env.JWT_SECRET_KEY; router.post('/registrasi', async (req, res) => { const { username, email, password } = req.body; if (!username || !email || !password) { return res.status(400).json({ error: 'Seluruh isian harus diisi' }); } const [ checkUsername ] = await db.query(`SELECT id FROM users WHERE username = '${username}'`); if (checkUsername.length > 0) { return res.status(400).json({ error: 'Username sudah terdaftar' }); } try { await db.query(` INSERT INTO users (username, email, password, status) VALUES ('${username}', '${email}', '${password}','activated'); `); res.status(200).json({ message: 'Registrasi berhasil', berhasil: true}); } catch (err) { res.status(500).json({ error: `Kesalahan:n${err}` }); } }); router.post('/login', async (req, res) => { const { username, password } = req.body; const [ userData ] = await db.query(`SELECT id, username, email, password FROM users WHERE username = "${username}" OR email = "${username}";`); // Find user by username or email const user = userData.find((user) => user['username'] === username || user['email'] === username); if (!user) { return res.status(401).json({ message: 'Username salah' }); } // Check password const isPasswordValid = await compare(password, user.password); if (!isPasswordValid) { return res.status(401).json({ message: "password salah" }); } // Create a JWT token const token = sign({ id: user.id, username: user.username }, SECRET_KEY, { expiresIn: '2h', }); return res.status(200).json({ message: 'Login successful', token, id: user.id, username: user.username }); }); // Protected route router.get('/protected', (req, res) => { const token = req.headers['authorization']; if (!token) { return res.status(403).json({ message: 'No token provided' }); } verify(token, SECRET_KEY, (err, decoded) => { if (err) return res.status(401).json({ message: 'Failed to authenticate token' }); // Proceed with the request return res.status(200).json({ message: 'Access granted', userId: decoded.id }); }); }); export default router; </code>
import dotenv from 'dotenv';  // Load environment variables from the .env file

import { Router } from 'express';
import { compare } from 'bcrypt';
import jwt from 'jsonwebtoken';
import { getUserByUserName } from '../databases/populate.postgre.js';
import db from '../databases/config.js';

dotenv.config();  // Load environment variables
dotenv.config({ path: '.env.development.local' }); // Load environment variables

const { sign, verify } = jwt;
const router = Router();

const users = [
  {
    id: 1,
    username: 'k1',
    email: '[email protected]',
    password: '$2a$12$zPlq1NLDZmgofBpy6LwiB.2q5zSU5TGQdk3Fh3Ll.PFYc7mrQXaAa' // bcrypt hash for 'ti3a'
  }
];

const SECRET_KEY = process.env.JWT_SECRET_KEY;

router.post('/registrasi', async (req, res) => {
  const { username, email, password } = req.body;
    
  if (!username || !email || !password) {
    return res.status(400).json({ error: 'Seluruh isian harus diisi' });
  }
  const [ checkUsername ] = await db.query(`SELECT id FROM users WHERE username = '${username}'`);
    
  if (checkUsername.length > 0) {
    return res.status(400).json({ error: 'Username sudah terdaftar' });
  }
  
  try {
    await db.query(`
      INSERT INTO users (username, email, password, status)
        VALUES ('${username}', '${email}', '${password}','activated');
    `);
    res.status(200).json({ message: 'Registrasi berhasil', berhasil: true});
  } catch (err) {
    res.status(500).json({ error: `Kesalahan:n${err}` });
  }
});
router.post('/login', async (req, res) => {
    const { username, password } = req.body;

    const [ userData ] = await db.query(`SELECT id, username, email, password FROM users WHERE username = "${username}" OR email = "${username}";`);
    // Find user by username or email
    const user = userData.find((user) => user['username'] === username || user['email'] === username);
    if (!user) {
      return res.status(401).json({ message: 'Username salah' });
    }

    // Check password
    const isPasswordValid = await compare(password, user.password);
    if (!isPasswordValid) {
      return res.status(401).json({ message: "password salah" });
    }

    // Create a JWT token
    const token = sign({ id: user.id, username: user.username }, SECRET_KEY, {
      expiresIn: '2h',
    });
    return res.status(200).json({ message: 'Login successful', token, id: user.id, username: user.username });
  });
  
  // Protected route
  router.get('/protected', (req, res) => {
    const token = req.headers['authorization'];
  
    if (!token) {
      return res.status(403).json({ message: 'No token provided' });
    }

    verify(token, SECRET_KEY, (err, decoded) => {
      if (err) return res.status(401).json({ message: 'Failed to authenticate token' });
      // Proceed with the request
      return res.status(200).json({ message: 'Access granted', userId: decoded.id });
    });
  });
  
  export default router;

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật