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
:
<code>import express from 'express';
import bodyParser from 'body-parser';
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 db from './databases/config.js';
import otpRoutes from './routes/otp.routes.js'; // Importing routes
import UserRoutes from './routes/user.routes.js'; // Importing routes
'http://localhost:', // Untuk web dari localhost
'http://http://10.0.2.2:', // Ganti dengan IP komputer host Anda
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');
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(`
// res.send(results[0].username);
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);
app.get('/cekOtp', async (req, res, next) => {
// const userId = parseInt(req.params.id, 10);
const [ result ] = await db.query(`
WHERE username = 'paksi4' AND email = '[email protected]';
const tipe = typeof result[0].otp;
// res.send(results[0].username);
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}`);
});
</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
:
<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;
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' });
INSERT INTO users (username, email, password, status)
VALUES ('${username}', '${email}', '${password}','activated');
res.status(200).json({ message: 'Registrasi berhasil', berhasil: true});
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);
return res.status(401).json({ message: 'Username salah' });
const isPasswordValid = await compare(password, user.password);
return res.status(401).json({ message: "password salah" });
const token = sign({ id: user.id, username: user.username }, SECRET_KEY, {
return res.status(200).json({ message: 'Login successful', token, id: user.id, username: user.username });
router.get('/protected', (req, res) => {
const token = req.headers['authorization'];
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 });
<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;