【发布时间】:2020-06-17 09:39:27
【问题描述】:
我知道这种问题以前已经解决了,但我无法弄清楚为什么它不适合我的情况。
我正在本地开发一个网站,我想在各种平台和设备上对其进行测试,所以我决定为此使用 ngrok。
我的前端在 3000 端口上运行,我的 express 服务器在 5000 端口上运行。
于是我打开ngrok,输入ngrok http 3000
在我运行服务器的本地 PC 上,https://example.ngrok.io 按预期工作,没有任何问题。
但在我的笔记本电脑(或其他设备)上,前端显示正确,但实际上要从后端获取数据时,却显示错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/weather/51.87575912475586,0.9436600208282471. (Reason: CORS request did not succeed).
在我的快递服务器上,我确保使用了 cors 包和app.use(cors());,我还尝试手动添加标题:
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
});
由于 localhost 的性质,这是否可行?
firefox 和 chrome 都有同样的问题。
感谢您的帮助!
【问题讨论】:
-
响应的 HTTP 状态码是什么?您可以使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?
-
嘿@sideshowbarker,感谢您的回复,很抱歉留下此信息。奇怪的是,请求根本没有状态码(此处显示:imgur.com/a/D3BJRkb),然后是控制台中的实际错误(imgur.com/a/XjYeysY)。当我从运行服务器的 PC 对 Postman 执行相同的请求时,请求很好并且通过了,但在我的笔记本电脑中它显示了这一点 (imgur.com/a/hDE34GR)。请注意,我之前还使用 OpenSSL 创建了 SSL 证书以使服务器为 https,但即使从我的本地 PC 也得到完全相同的错误。
标签: node.js express cors localhost ngrok