我在英国工作。我正在使用Axios。在我的一个组件中发布('/api/users/login',value)
。现在我想将userName
和passWord
存储在一个文件中,并使用Axios
从本地文件获取值。我想有一个固定的用户名和密码用户登录。
是否可以使用Axios.post()从本地文件获取值?
当我尝试时,它不起作用,但我认为您应该尝试使用node的fs
本机模块。js,可以访问文件系统。
您可以使用原生javascriptFileReader
在浏览器中读取它,然后根据您的需要进行处理/操作。在这种情况下,文件内容如下credentials.txt
userName: email@domain.com
passWord: yourpassword
JSX
<input type="file" onChange={this.openFile.bind(this)} />
onChange处理程序
openFile(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = () => {
const arr = reader.result.split(/\r?\n/);
this.login({
userName: arr[0].split(":")[1],
passWord: arr[1].split(":")[1]
});
};
reader.readAsText(input.files[0]);
}
登录方法
login(loginObj) {
// make api calls
axios.post("/api/users/login", loginObj).then(resp => {
// do your stuff
});
}
代码沙箱https://codesandbox.io/s/crazy-feynman-vjtxo
干杯