我正在尝试使用fetch().
向URL发送一个POST请求
我有意设置授权头,但是当我检查Firefox中的响应时,它会输出错误“String类型的方法参数缺少请求头‘授权’。
var target_url = "https://api.sonos.com/login/v3/oauth/access";
var encoded_msg = btoa(client_id + ':' + secret); // base64-encodes client_id and secret using semicolon as delimiter
var params = `grant_type=authorization_code` + `&code=${authCode}` + `&redirect_uri=${redirect_uri}`;
var myHeaders = new Headers({
'Authorization': `Basic ${encoded_msg}`,
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Content-Length': params.length,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
fetch(target_url, {
method: 'POST',
mode: 'no-cors',
credentials: 'include',
redirect: 'follow',
headers: myHeaders,
body: params
})
.then(response => {
console.log("Status: " + response.status);
console.log("StatusText: " + response.statusText);
console.log("Type: " + response.type);
console.log("URL: " + response.url);
});
是什么移除授权头,为什么以及如何防止它?
编辑:
为了澄清这一点,我使用Firebase函数来承载我的网页,我从该页面将请求发送到Sonos授权API。
使用邮递员,请求通过,我得到正确的反应。
发布于 2020-07-23 03:26:44
要检索访问令牌所执行的步骤必须在云函数端点中执行。
获得访问令牌 获得授权代码后,使用它获取访问令牌和刷新令牌。使用访问令牌通过Sonos云向家庭发送API调用。这个步骤使用您的客户端机密,因此应该是服务器端请求,而不是客户端(基于浏览器的)请求。参考资料:https://developer.sonos.com/build/direct-control/authorize/
将节点取作为package.json
中的依赖项引入,因为它的API实现与浏览器fetch密切相关。
添加端点如下:
const fetch = require('node-fetch');
const functions = require('firebase-functions');
const secret = functions.config().sonos.secret;
const client_id = functions.config().sonos.client_id;
const redirect_uri = functions.config().sonos.redirect_uri;
exports.retrieveAccessToken = functions.https.onRequest(async (req, res) => {
const {authCode} = req.query;
const target_url = "https://api.sonos.com/login/v3/oauth/access";
const encoded_msg = btoa(`${client_id}:${secret}`); // base64-encodes client_id and secret using semicolon as delimiter
const body = `grant_type=authorization_code&code=${authCode}&redirect_uri=${redirect_uri}`;
const headers = new Headers({
'Authorization': `Basic ${encoded_msg}`,
'Content-Length': body.length,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
const response = await fetch(target_url, {
method: 'POST',
redirect: 'follow',
headers,
body
});
const token_data = await response.json();
return token_data;
});
修改网页中的代码,在用户从Sonos登录服务返回后向云功能端点发出请求。
const authCode = new URLSearchParams(window.location.search).get('code');
fetch(`https://us-central1-<project-id>.cloudfunctions.net/retrieveAccessToken?authCode=${code}`);
https://stackoverflow.com/questions/63050559
复制相似问题