[英]How to Form Authentication Header for Axios Request to Node.js App Using Passport Local Authentication?
我有一個 node.js 應用程序,正在開發一個單獨的單頁應用程序(最終將轉換為 Android 和 iOS 本機應用程序)。 我正在 node.js 應用程序上設置 API 並且正在努力進行身份驗證。 node.js 應用程序使用passport-local-mongoose
進行身份驗證,我將用戶數據存儲在MongoDB 后端。 對於測試/開發,單頁應用程序在http://localhost:1234/
。
我的端點看起來像:
exports.getDevicesAPI = async (req, res) => {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers: Authorization');
const devices = await Device.find({ owner: req.user._id });
res.json(devices);
};
我可以GET
像這樣的東西沒有問題:
const axios = require('axios');
const url = 'http://localhost:7777/api/devices';
function getDevices() {
axios
.get(url)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
我想添加authenticate = passport.authenticate('header', {session: false, failWithError: true});
在服務器端提供身份驗證,但以下內容讓我Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7777/api/devices. (Reason: CORS header 'Access-Control-Allow-Origin' missing)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7777/api/devices. (Reason: CORS header 'Access-Control-Allow-Origin' missing)
:
const axios = require('axios');
const url = 'http://localhost:7777/api/devices';
const username = myUsername;
const password = myPassword;
const axiosConfig = {
headers: {
'Content-Type': 'application/json',
},
Authorization: {
username,
password,
},
};
function authenticate() {
axios
.post(url, axiosConfig)
.then(function(response) {
console.log('Authenticated');
})
.catch(function(error) {
console.log('Error on Authentication');
});
}
路線(用於測試):
router.get('/api/devices', catchErrors(deviceController.getDevicesAPI));
router.post('/api/devices', catchErrors(deviceController.getDevicesAPI));
我錯過了什么?
您遇到了 CORS(跨源資源共享)限制問題。 在此處閱讀有關 CORS 的更多信息。
我相信這部分代碼是為了處理 CORS:
exports.getDevicesAPI = async (req, res) => {
// ...
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers: Authorization');
// ...
};
但是,這里的錯誤是這些 CORS 標頭的設置與路由相關聯,即不應該是getDevicesAPI
路由。 對於可能修改另一個源中資源的請求(例如 POST 到getDevicesAPI
路由),瀏覽器會在發送實際請求之前首先使用OPTIONS
Http 方法發送預檢請求,對預檢請求的響應是必要的 CORS預計將設置響應標頭。 您可以在此處找到有關預檢請求的說明。
我通常會在其他路由上方添加這樣的中間件:
router.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', '*');
next();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.