I am having a weird issue with a MERN app I am making. When I access to my React front-end and try to log into my app, the following error message appears:
Failed to execute 'fetch' on 'Window': Failed to parse URL from https://<my_ip_address>:9901/api/auth/sign_in
And that is very weird considering that I’m making sure that my server is running on HTTPS and it’s on port 9901:
const https = require('https');
const express = require('express');
const fs = require('fs');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const ApiRouter = require('./src/routers/ApiRouter');
const path = require('path');
const cors = require('cors');
const os = require('os');
const { DB_LINK, BASE_URL, NODE_ENV } = require('./src/config/config');
const app = express();
const whitelist = ['http://localhost:3000'];
function getLocalIpAddress() {
const interfaces = os.networkInterfaces();
for (const key in interfaces) {
const iface = interfaces[key];
for (let i = 0; i < iface.length; i++) {
const alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
return alias.address;
}
}
}
return null;
}
const localIpAddress = getLocalIpAddress();
if (localIpAddress) {
whitelist.push(`http://${localIpAddress}:3000`);
}
// I know this is not secure, this is only for develipment purposes
app.use(
cors({
origin: function (origin, callback) {
callback(null, true);
}
})
);
// Load SSL certificate
const credentials = {
pfx: fs.readFileSync('sslcert/cert/localhost.p12'),
passphrase: 'changeit'
};
// Use HTTPS
const httpsServer = https.createServer(credentials, app);
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
express.static.mime.types['css'] = 'text/css';
app.use(express.static('public'));
app.use('/uploads', express.static(path.join(__dirname, './uploads')));
mongoose.connect(DB_LINK, {
useNewUrlParser: true,
useUnifiedTopology: true,
retryWrites: true,
connectTimeoutMS: 10000
})
.then(() => {
app.use('/api', ApiRouter);
const port = 9901;
httpsServer.listen(port, () => {
console.log('Connected to MongoDB');
// BASE_URL = 'https://<my_ip_address>:9901';
console.log(`Server started at ${BASE_URL}/`);
console.log(`Environment: ${NODE_ENV}`);
});
})
.catch((err) => {
console.error(err);
process.exit(1);
});
Then, in my client, I have the following configuration file that defines the URL where my backend is running so my endpoint calls (or ‘fetch’ requests) know where it is. This file is called basePath.js:
const serverBaseUrl = process.env.REACT_APP_SERVER_BASE_URL || '<my_ip_address>';
export const basePath = `https://${serverBaseUrl}:9901/api`;
So, as you can imagine, I observed the following condition:
- The port number for my server is the correct one since it’s the one defined in my server’s configuration.
- Right now my CORS configuration allows requests for any origin. This is strictly for development purposes only.
- Both my client and server are running correctly and on the same network (since I am running them on my local machine).
- My API route is implemented in my server:
router.post('/sign_in', async (req, res, next) => {
const { email, password } = req.body;
try {
const authData = await signIn(email, password);
res.json(authData);
} catch (error) {
errorCallback(error, res);
}
});
and in my client:
import { getJSONHeaders } from '../../functions/sharedHeaders';
import { basePath } from '../../config/basePath';
...
async function signIn({ email, password }) {
const response = await fetch(`${basePath}/auth/sign_in`, {
method: 'POST',
body: JSON.stringify({ email, password }),
headers: getJSONHeaders()
});
const { user, token, refreshToken, message, success } = await response.json();
...
}
So, what could be my issue here?