我知道这种问题以前已经解决了,但我无法弄清楚为什么它对我的情况不起作用。
我在本地网站上工作,我想在各种平台和设备上测试它,所以我决定为此使用 ngrok。
我的前端在端口 3000 上运行,而我的 express 服务器在端口 5000 上运行。
于是我打开ngrok,输入ngrok http 3000
在我的本地 PC 上,服务器正在运行,https://example.ngrok.io
正常工作,没有任何问题。
但是在我的笔记本电脑(或其他设备)上,前端显示正确,但是当它真正要从后端获取数据时,却显示错误:Cross-Origin Request Blocked: The同源策略不允许读取位于 http://localhost:5000/weather/51.87575912475586,0.9436600208282471 的远程资源。 (原因:CORS请求没有成功)
在我的 express 服务器上,我确保使用了 cors 包和 app.use(cors());
并且我还尝试手动添加 header :
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
来源:Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
这也是我获取和获取数据的代码,以防我在那里做错事:
index.js(前端)
const response = await fetch(`http://localhost:5000/weather/${lat},${lng}`); //sending request to server-side
const json = await response.json();
console.log(json); //getting the weather data from server-side
server.js(后端)
const express = require("express");
const mongoose = require("mongoose");
const fetch = require("node-fetch");
const cors = require('cors');
const nodemailer = require('nodemailer');
require('dotenv').config();
const users = require('./routes/api/users');
const app = express();
//Json Middleware
app.use(express.json());
app.use(cors());
//Getting URI from keys file
const db = require('./config/keys').mongoURI;
//Connect to the Database
mongoose.set('useUnifiedTopology', true);
mongoose.set('useCreateIndex', true);
mongoose.connect(db, {useNewUrlParser: true})
.then(()=> console.log("Database Connected"))
.catch(err=> console.log(err));
//Route for user routes
app.use('/api/users',users);
const dbport = process.env.PORT || 5000;
app.listen(dbport, () => console.log(`Server started on port ${dbport}`));
app.get('/weather/:latlon', async (req,res) =>{ //awating request from client-side
const latlon = req.params.latlon.split(',');
console.log(req.params);
const lat = latlon[0];
const lon = latlon[1];
console.log(lat,lon);
const api_key = process.env.API_KEY;
const weather_url = `https://api.darksky.net/forecast/${api_key}/${lat},${lon}?units=auto`; //getting data from weather API
const fetch_res = await fetch(weather_url);
const json = await fetch_res.json();
res.json(json); //sending weather data back to client-side
});
由于本地主机的性质,这是否可行?
firefox 和 chrome 都有同样的问题。
感谢您的帮助!
最佳答案
经过几天的摸索,我终于找到了解决方案,我将其发布在下面,以供可能遇到相同问题的其他人使用。
第一步:
我没有激活 2 个端口(客户端 3000 个,服务器 5000 个),而是关闭了客户端端口并使用 express 直接从服务器提供客户端文件夹/ Assets :
const dbport = process.env.PORT || 5000;
app.listen(dbport, () => console.log(`Server started on port ${dbport}`));
app.use(express.static('client')); //serving client side from express
//Json Middleware
app.use(express.json());
第 2 步:
现在我们有一个端口(端口 5000)用于客户端和服务器,我进入我的客户端,在那里我执行我的获取请求(参见上面的 index.js)并将实际请求修改为相对的:
const response = await fetch(`/weather/${lat},${lng}`); //sending request to server-side
const json = await response.json();
console.log(json); //getting the weather data from server-side
第 3 步:
最后,我打开 ngrok 并输入:
ngrok http 5000
它现在应该可以工作了。
关于node.js - 为什么在通过 ngrok 建立隧道时会出现 CORS 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60533796/