Note: I'm new to node.js and its my first time for hosting web on vercel and railway
I'm building a portfolio website using Vue.js for the frontend (hosted on Vercel) and Express for the backend (hosted on Railway). I’m making an API request from the frontend to the backend using Postman, but I'm getting this:
{
"status": "error",
"code": 502,
"message": "Application failed to respond",
"request_id": "qRGtgXEgRh-ujLV1YFPJ3Q_2621307460"
}
The request is made to following endpoint https://lunarexpress.lunartechlab.com/api/send-mail
My CORS configuration for backend looks like
const express = require("express");
const cors = require("cors");
const app = express();
const corsOptions = {
origin: "https://lunartechlab-zelino.vercel.app",
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type"],
credentials: true,
};
app.use(cors(corsOptions));
app.options("*", cors(corsOptions));
Backend Setup: I have verified that the backend is responding to requests, but the CORS issues and 502 Preflight error still persist.
I’m using Express to serve the backend API, and I am serving the frontend from the dist directory using express.static.
app.use(express.static(path.join(__dirname, "../../vuejs/dist")));
// Serve the frontend application for all other requests
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../../vuejs/dist/index.html")); // Adjust the path
});
but not serving request from dist on vercel as my vercel.json for vue looks like:
{
"rewrites": [
{ "source": "/api/(.*)", "destination": "https://your-api-endpoint.com" },
{ "source": "/(.*)", "destination": "/index.html" }
]
}
also i'm not sure that should i define api url here in vercel my code for sending api requests to serer from client looks like
import axios from "axios";
// register a user
export const sendEmail = async (formData) => {
try {
const response = await axios.post(
"https://lunarexpress.lunartechlab.com/api/send-mail",
formData
);
return response.data;
} catch (err) {
throw err;
}
};
use fetch instead of axios,
other thing to keep in mind, if you are sending api request from postman try thunder client extension in vscode you should use http://localhost:5000/...
, instead of "https://localhost:5000/...
and the cors ; like this
const corsOptions = {
origin: process.env.CLIENT_URL || "http://localhost:3000", // Frontend URL
};