我想使用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。不过,我不知道为什么会发生这种情况
答案 0 :(得分:-1)
我相信您没有设置CORS
选项。请尝试以下操作:
const express = require('express');
const app = express();
const cors = require('cors');
require('dotenv/config');
// CORS Options: But customise according to your needs
const options = {
allowedHeaders: ["Origin", "Content-Type", "Accept", "Authorization"],
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
origin: "*",
preflightContinue: false
};
// Middlewares
app.use(cors(options));
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);