javascript - 如何防止我的获取请求出现 CORS 和混合内容错误
问题描述
所以我一直试图让我的网站从我的 nodejs/expressjs 应用程序中获取数据,我让客户端网站在 localhost 上接收数据没有问题,但是一旦我将它部署到服务器上,我就开始出现混合内容错误,所以我继续为我的 expressjs 应用程序添加 https 中间件,但后来我收到了 CORS 错误。
我也将 res.header 原点设置为“*”,但它仍然返回一个 cors 错误,我希望我只是忽略了一些简单的事情,但我觉得我有点超出我的深度
是的,我知道我的 jankie auth 中间件,我还没有获得 JWT 令牌,我还是个初学者
目前我正在使用像这样的 url 方案
使用 apiUrl='https://api.mysite.com:3502' 获取客户端网站“https://build.mysite.com”
和nodejs地址'https://api.mysite.com'
这是客户端获取功能
import { apiUrl } from "../global-variables.js";
async function getApiNav(target, version = null) {
// declaring the item to target from the database
target = `?target=${target}`;
// declaring the version number if it is passed in arguments
if (version == null) {
version = "";
} else if (typeof version == "number") {
version = `&version=${version}`;
}
try {
const res = await fetch(`${apiUrl}/product/nav${target}${version}`);
const apiRes = await res.json();
return apiRes;
} catch (error) {
console.log(
`There was an error requesting navigation data from mysite.com${error}`
);
}
}
export default getApiNav;
这是节点应用程序的主要 app.js 文件
// Loading Environment Variables
require("dotenv").config({ path: `/var/www/env/.env` });
require("dotenv").config();
console.log(`*** Using ${process.env.NODE_ENV} Environment Variables ***`);
const {
DB_CONNECT: Database,
CORS: corsOrigin,
DEV_URL: devUrl,
PORT: port,
HTTPS_PORT: httpsPort,
POST_CRED: postPassword,
} = process.env;
// Dependancies
const express = require("express");
const https = require("https");
const path = require("path");
const fs = require("fs");
const app = express();
const mongoose = require("mongoose");
const { NavVersionCheck } = require("./functions/nav/navFunctions");
// Connect to database -------------------------------------------------------------------------------
mongoose.connect(
Database,
{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
},
() => {
console.log("*** Connected to DB ***");
// Version check and print for database collections
NavVersionCheck("header", true);
NavVersionCheck("sideNav", true);
}
);
// Middleware ---------------------------------------------------------------------------------------
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json({ limit: "1mb" }));
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", corsOrigin);
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.header("Access-Control-Allow-Headers", "Content-Type");
next();
});
// Checks the request body for the password so that you can post to the database
app.use((req, res, next) => {
req.body.auth = false;
req.body.password === postPassword
? (req.body.auth = true)
: (req.body.auth = false);
next();
});
// Import Routes
const NavRoutes = require("./routes/nav/navNavRoutes");
const ContentRoutes = require("./routes/nav/navContentRoutes");
const SpecRoutes = require("./routes/nav/navSpecRoutes");
// Routes --------------------------------------------------------------------------------------------
app.use("/nav/nav", navNavRoutes);
app.use("/nav/content", navContentRoutes);
app.use("/nav/spec", navSpecRoutes);
app.get("/", (req, res) => {
res.json({ message: `this is the root api` });
});
// Port Listeners -----------------------------------------------------------------------------------
app.listen(port, (err) => {
if (err) {
return console.log("ERROR ", err);
}
console.log(`*** Listening on port ${port} ***`);
});
//
const httpOptions = {
cert: fs.readFileSync(path.join(__dirname, "ssl", "cert.pem")),
key: fs.readFileSync(path.join(__dirname, "ssl", "key.pem")),
};
//
https.createServer(httpOptions, app).listen(httpsPort, (err) => {
if (err) {
return console.log("ERROR ", err);
}
console.log(`*** Listening on HTTPS port ${httpsPort} ***`);
});
//
还有我这个项目的 nginx 路由是
server {
root /var/www/nodejs;
index index.html index.htm index.nginx-debian.html;
server_name api.mysite.com www.api.mysite.com;
location / {
proxy_pass http://127.0.0.1:3500;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
listen [::]:443 ssl; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.mysite.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.mysite.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = www.api.mysite.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
if ($host = api.mysite.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
listen 80;
listen [::]:80;
server_name api.mysite.com www.api.mysite.com;
return 404; # managed by Certbot
}
解决方案
推荐阅读
- django - 使用 Django 视图值更新 JavaScript
- python - Pandas pivot_table 发出关于在日期类型的数据集上使用边距时推断 datetime64 的 FutureWarning
- flutter - 购买后不调用函数
- android - 布局检查器未显示可组合树
- html - 服务器代码是持续运行还是仅在用户发出请求时运行?
- bash - 安装了两个版本的 bash,来自终端的关于我正在使用哪个版本的信息冲突
- android-studio - 检查 URL 连接 Android Studio
- html - SVG 中的等宽字体具有可变宽度字形
- javascript - child() 不是函数图片上传 firebaseSDK Ver9 for Web (JavaScript)
- python - 事件循环关闭 discord.py