【发布时间】:2019-12-04 14:52:39
【问题描述】:
我想使用 express 获取我的数据。代码如下:
const express = require('express');
const app = express();
const cors = require('cors');
require('dotenv/config');
// Middlewares
app.use(cors());
app.use(express.json());
// Routes
const postRouter = require('./routes/posts');
app.use('/posts', postRouter);
// Mongoose connect
const mongoose = require('mongoose');
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => console.log("You are connected to MongoDB")
);
// Port listen
app.listen(2998);
这些 node+express 代码使用 Postman 完美运行。
但是当我使用 javascript 获取时它总是显示 CORS 错误。这是JS代码:
let url = "https://localhost:2998/posts/"
fetch(url)
.then(result => {
console.log(result);
})
.then(data => {
console.log("data: " + data)
});
控制台说:
跨域请求被阻止:同源策略不允许读取位于https://localhost:2998/posts/ 的远程资源。 (原因:CORS 请求未成功)。
。 . . . .
已解决!它只是无法运行 https 协议,所以我需要将其更改为http://localhost/2998。不过,我不知道为什么会这样
【问题讨论】:
-
你的 localhost 使用的是 https 协议?
-
是的,https 有什么问题吗?反正我是新手,呵呵
-
不,只是交叉验证,如果有帮助试试这个stackoverflow.com/questions/18310394/…
-
“已解决!它只是无法运行 https 协议”——这根本没有意义,因为您说使用邮递员时它可以工作。除非您更改了切换到 JS 时使用的 URL……这非常重要!