我编写了一个应用程序,该应用程序在客户端使用react
,在后端使用express
和keystone.js
。
我的问题是,每当我提交包含email and password
的登录表单时,浏览器都会发送OPTIONS
请求而不是POST
请求。根据我所做的研究,看来我很可能CORS
有问题。我尝试了几种方法来解决这个问题。
这是我从react
应用发送的请求:
function login(email, password) {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password })
};
return fetch(`${url}authenticate`, requestOptions)
.then(handleResponse)
.then(user => {
// login successful if there's a jwt token in the response
if (user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem("user", JSON.stringify(user));
}
return user;
});
}
我的keystone.js
文件中有一些代码,我尝试使用cors
库来解决该问题,但是没有运气。
var keystone = require("keystone");
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.options("*", cors());
keystone.set("routes", app);