Php Can';t访问api post方法,始终请求选项
我试图创建一个登录表单,使用nuxtjs作为前端,slim php作为后端api,当我试图访问api时,我看到我发送的请求方法是选项而不是POST,在chrome开发控制台中,错误显示请求被阻止(CORS)。 我知道我必须设置访问控制允许方法向其中添加选项,但仍然失败,在nuxt js(nuxt.config)或slim php中在哪里设置 我曾尝试从postman访问api,但效果很好,我可以看到access Control Allow Methods标头中有选项,但在vue应用程序中尝试时仍然失败Php Can';t访问api post方法,始终请求选项,php,vue.js,axios,slim,nuxt.js,Php,Vue.js,Axios,Slim,Nuxt.js,我试图创建一个登录表单,使用nuxtjs作为前端,slim php作为后端api,当我试图访问api时,我看到我发送的请求方法是选项而不是POST,在chrome开发控制台中,错误显示请求被阻止(CORS)。 我知道我必须设置访问控制允许方法向其中添加选项,但仍然失败,在nuxt js(nuxt.config)或slim php中在哪里设置 我曾尝试从postman访问api,但效果很好,我可以看到access Control Allow Methods标头中有选项,但在vue应用程序中尝试时仍
commons.app.js:434 OPTIONS http://localhost:8080/login 401 (Unauthorized)
Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
来自slimphp(API)的代码
routes.php
// login routes
$app->post('/login', function (Request $request, Response $response, array $args) {
$input = $request->getParsedBody();
$sql = "SELECT * FROM groups
LEFT JOIN users_groups ON groups.groups_id = users_groups.users_groups_id
LEFT JOIN users ON users_groups.users_groups_id = users.id
WHERE users.email = :email";
$sth = $this->db->prepare($sql);
$sth->bindParam("email", $input['email']);
$sth->execute();
$user = $sth->fetchObject();
// verify email address.
if (!$user) {
$container->get('logger')->info("Error trying to login with email : ".$input['email']);
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
}
// verify password.
if (!password_verify($input['password'], $user->password)) {
$container->get('logger')->info("Error trying to login with password : ".$input['password']);
return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']);
}
// cek apakah sudah login sebelumnya hari ini untuk user ini
$absensiSql = "SELECT * FROM users_presensi WHERE user_id = :userID";
$sth = $this->db->prepare($absensiSql);
$sth->bindParam("userID", $user->id);
$sth->execute();
$absensi = $sth->fetchObject();
// jika belum absen, masukan user ke absensi
if(!$absensi){
$status = 1;
$absensiSql = "INSERT INTO users_presensi(user_id, statuss) VALUES (:userID, :statuss)";
$sth = $this->db->prepare($absensiSql);
$sth->bindParam("userID", $user->id);
$sth->bindParam("statuss", $status);
$sth->execute();
// $absensi = $sth->fetchObject();s
}
$settings = $this->get('settings'); // get settings array.
$token = JWT::encode(['id' => $user->id, 'email' => $user->email, 'level' => $user->groups_level], $settings['jwt']['secret'], "HS256");
// i already set the header here
return $this->response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->withHeader('Set-Cookie', "token=$token; httpOnly")
->withJson(['token' => $token]);
})->setName('login');
我的nuxtjs身份验证配置
nuxt.config.js
/*
** Nuxt.js modules
*/
modules: [
'@nuxtjs/vuetify',
// Doc: https://axios.nuxtjs.org/usage
'@nuxtjs/axios',
'@nuxtjs/pwa',
'@nuxtjs/eslint-module',
'@nuxtjs/auth'
],
/*
** Axios module configuration
** See https://axios.nuxtjs.org/options
*/
axios: {
},
/**
* set auth middleware
*/
router: {
middleware: ['auth']
},
auth: {
strategies: {
local: {
endpoints: {
login: { url: 'http://localhost:8080/login', method: 'post', propertyName: 'token' }
}
// tokenRequired: true,
// tokenType: 'bearer'
}
}
}
方法从login.vue登录
loginPost: function () {
this.$auth.loginWith('local', {
data: {
username: this.loginData.username,
password: this.loginData.password
}
})
}
在postman中,结果是令牌本身,我认为不应该发生cors错误,但谁知道呢。我不知道其他浏览器,但我知道Chrome不支持在
访问控制允许源文件头中使用localhost。您应该在您的开发环境中只告诉它接受所有来源->with header('Access-Control-Allow-Origin','*')
选项请求是为浏览器发送实际请求以确定CORS规则而发送的请求。我按照您的建议编辑代码(routes.php),但即使在响应头中(在chrome dev中),仍然不起作用显示访问控制允许标题:内容类型
访问控制允许方法:获取、放置、发布、删除、标题、选项
访问控制允许来源:
我也尝试过安装CORS(chrome扩展)我的问题仍然存在。我想到了两件事:我知道一些后端框架期望所有POST请求的内容类型为application/x-www-form-urlencoded
,axios将其设置为application/javascript
。我不知道loginWith
函数是如何工作的,但我在项目中使用Nuxt中间件时遇到了麻烦。我不记得那些麻烦发生在哪里了,但我直接调用了$axios.post
和$axios.get
函数,这对我很有用。你可以看看这个答案。也许对你有帮助。哎呀,我忘了在我的slim应用程序中,我使用的是Corsmidlware(使用tuupola),我忘了设置它。我很高兴你能找出问题所在。