我想用fetch写一个简单的基本身份验证,但我一直得到一个401错误。如果有人告诉我代码有什么问题,那就太棒了:
let base64 = require('base-64');
let url = 'http://eu.httpbin.org/basic-auth/user/passwd';
let username = 'user';
let password = 'passwd';
let headers = new Headers();
//headers.append('Content-Type', 'text/json');
headers.append('Authorization', 'Basic' + base64.encode(username + ":" + password));
fetch(url, {method:'GET',
headers: headers,
//credentials: 'user:passwd'
})
.then(response => response.json())
.then(json => console.log(json));
//.done();
我将分享一个具有基本认证头表单数据请求体的代码,
let username = 'test-name';
let password = 'EbQZB37gbS2yEsfs';
let formdata = new FormData();
let headers = new Headers();
formdata.append('grant_type','password');
formdata.append('username','testname');
formdata.append('password','qawsedrf');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
fetch('https://www.example.com/token.php', {
method: 'POST',
headers: headers,
body: formdata
}).then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({
data: responseJson
})
})
.catch((error) => {
console.error(error);
});
节点用户(react, express)遵循这些步骤
NPM安装base-64
Import {encode} from "base-64";
const response = await (URL, {
方法:“文章”,
headers: new headers ({
“授权”:“基本”+编码(用户名+“:”+密码),
“内容类型”:“application / json”
}),
身体:JSON.stringify ({
:“PassengerMobile xxxxxxxxxxxx”,
“密码”:“xxxxxxx”
})
});
Const posts = await response.json();
不要忘记将整个函数定义为async
一个简单的复制粘贴到Chrome控制台的例子:
fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}})
.then(response => response.json())
.then(json => console.log(json));
或者带着等待:
let response = await fetch('https://example.com/path', {method:'GET',
headers: {'Authorization': 'Basic ' + btoa('login:password')}});
let data = await response.json();
console.log(data);
get请求与授权的React原生移动应用程序,我已经花了更多的时间在fetch里面搜索这些行
var base64 = require("base-64"); // install it before use from npm i base-64
const uname = "some username goes here";
const pword = "some password goes here";
const getMovies = async () => {
try {
const response = await fetch(
"API URL goes here",
{
headers: {
Authorization: "Basic " + base64.encode(uname + ":" + pword),
},
}
);
data = await response.json();
setData(data);
console.log(data);
// console.log(data.name);
return data;
} catch (error) {
console.error(error);
} finally {
setLoading(false);
}
};
useEffect(() => {
getMovies();
}, []);
// other code
// inside return
<FlatList
keyExtractor={(item) => item.id}
data={data}
renderItem={({ item }) => (
<View style={styles.text_container}>
<Text>{item.name}</Text>
<Text>{item.images[0].name}</Text>
<Text>{item.images[0].src}</Text>
</View>
)}
/>