我有我的应用程序设置,并在带有代理的 Express 服务器上运行以与 API 服务器通信,我的代码概述如下
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/[email protected]/dist/vue.global.js" defer></script>
<script src="app.js" defer></script>
</body>
</html>
我的 App.js 设置如下,相当标准:
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')
我的 server.js(由 ExpressJS 提供支持)也在下面...
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');
});
所以我运行
npm run start
来启动我的 server.js
没问题,目的是用客户 ID 填充输入框并点击“他们合法吗?”按钮来检查客户是否真实,代理会跳转检查 /checkCustomer
,然后删除 /checkCustomer
并将其余 URL 附加到 API url 并提交。
但是情况似乎并非如此,我只是在控制台中得到
{success: true}
。我没有收到任何响应数据,也没有收到任何表明出现问题的迹象。
当前的所有配置方式都是为了尝试解决 CORS 问题。
我在 stackOverflow 上尝试了一些文章/问答,谷歌搜索了一些解决方案,但没有任何结果,这是我得到的最接近的。
有人可以指导我解决这个问题吗?
无论 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()
});
如您所见,它发送了响应。因此,它会妨碍特定于 API URL 的代码
/checkCustomer
。
您可能想删除
res.status(200).json({ success: true});
语句。或者,如果您希望将其用于其他 URL,则需要将其设置为条件或类似的。