I have my app setup, and running on an express server with a proxy to talk to the API server, my code is outlined below
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Is That Legit?</title>
<link rel="stylesheet" href="assets/main.css">
</head>
<body>
<div id="app">
<div class="wrapper">
<header>
<img alt="Site logo" class="logo" src="assets/logo.svg" width="333" height="187" />
</header>
<h1 class="app-title">Is User Legit</h1>
<input @input="saveID" placeholder="User ID" />
<button @click="checkID">Check Customer is Legit</button>
</div>
</div>
<script src="https://unpkg.com/vue@3.4.9/dist/vue.global.js" defer></script>
<script src="app.js" defer></script>
</body>
</html>
My App.js is setup like this, fairly standard:
const app = Vue.createApp({
data() {
return {
customerID: ''
}
},
methods: {
saveID(event) {
this.customerID = event.target.value;
},
async checkID() {
const options = {
method: 'GET',
headers: {
Accept: 'application/json',
'x-api-key': 'ThisIsMyAPIKeyThereIsNoOtherLikeIt'
}
}
const url = `/checkCustomer?customerNumber=${this.customerID}`;
try {
const result = await fetch(url, options);
const json = await result.json();
console.log(json);
} catch (error) {
console.error(error);
}
},
}
})
app.mount('#app')
my server.js (which is powered by ExpressJS) is also below…
const express = require('express');
const https = require('https');
const cors = require('cors');
const { createProxyMiddleware } = require('http-proxy-middleware');
const fs = require('fs');
const app = express();
// app.use(cors());
app.use(express.static('dist'));
app.use('/dist', (req, res) => {
res.sendFile(__dirname + 'dist/index.html');
});
app.use('/dist/assets/main.css', (req, res) => {
res.sendFile(__dirname + 'dist/assets/main.css');
});
app.use(express.json());
app.use(
cors({
origin: ['https://myAPI.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
})
);
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With')
res.status(200).json({ success: true});
next()
});
// Add middleware for http proxy
const options = {
target: 'https://myAPI.com', // target host
pathRewrite: {
'^/checkCustomer' : ''
},
router: {
'localhost:3000': 'https://myAPI.com',
},
};
const apiProxy = (req, res) => {
createProxyMiddleware(options);
}
app.use('/checkCustomer', apiProxy);
https.createServer(
{
key: fs.readFileSync("thisIsMyServerKey.key"),
cert: fs.readFileSync("thisIsMyServerCert.cert"),
},
app
).listen(3000, () => {
console.log('Listening on: https://localhost:3000');
});
So I run npm run start to fire up my server.js no problem, and the aim is to populate the input box with a customer ID and hit the "Are They Legit?" button to check if a customer is real or not, the proxy jumps in checking for the /checkCustomer it then removes the /checkCustomer and appends the rest of the URL tot he API url and submits it.
However this doesn’t appear to be the case, and I just get {success: true} in the console. I don’t get any response data, and I don’t get any indication as to the fact that anything is wrong.
everything is currently configured the way it is to try and resolve an issue with CORS.
I tried a few articles/Q&A on stackOverflow, googling a few solutions, but nothing has come to fruition, this was the closest I have got.
Would someone be able to guide me in fixing this?
>Solution :
This code runs unconditionally, regardless of the URL:
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With')
res.status(200).json({ success: true}); // <============================ Note!
next()
});
As you can see, it sends a response. So it’s getting in the way of your code that’s specific to the API URL /checkCustomer.
You probably want to remove the res.status(200).json({ success: true}); statement. Or if you want it for other URLs, you’ll want to make it conditional or similar.
Separately: I’ve never used that proxy middleware, but it seems like apiProxy should return the result of createProxyMiddleware so the proxy goes to app.use. (Currently apiProxy doesn’t return anything, because an arrow function with a { just after the => uses a full function body, so you’d need a return to return the result of the createProxyMiddleware call.)