我是ReactJS的新手,并且我已经使用simple-oauth
连接到测试API。我添加了客户端ID,客户端密码,用户名和密码以及oauth令牌URL。我收到语法错误await is a reserved word (40:21)
下面是我当前的代码,它是来自simple-oauth的示例:-
const credentials = {
client: {
id: "CLIENT_ID",
secret: "CLIENT_SECRET"
},
auth: {
tokenHost: "http://localhost/oauth/token"
}
};
const oauth2 = require('simple-oauth2').create(credentials);
const tokenConfig = {
username: "USERNAME",
password: "PASSWORD",
scope: '<scope>',
};
try {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
} catch (error) {
console.log('Access Token Error', error.message);
}
我也尝试了异步功能。尽管错误消失了,但控制台日志并未被触发。这是异步功能代码:-
async () => {
const result = oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
// no console.log in the debugger
console.log(result);
};
代码中可能有什么问题?请帮忙。
答案 0 :(得分:1)
我也尝试了异步功能。虽然错误消失了,但控制台日志 没有被触发。
因为您没有调用函数。您需要的是Self Invoking Function
:
(async () => {
const result = oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
// no console.log in the debugger
console.log(result);
})();
答案 1 :(得分:0)
未触发代码行。您将需要包装到async函数中,然后从componentDidMount
某个合适的位置调用该函数。
const funcName = async () => {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const accessToken = oauth2.accessToken.create(result);
// no console.log in the debugger
console.log(result);
};
componentDidMount(){
this.funcName();
}
答案 2 :(得分:0)
您必须将componentWillMount
(或componentDidMount
)声明为async
才能使用await
。您可以通过更改签名来做到这一点:
async componentWillMount() {
const result = await oauth2.ownerPassword.getToken(tokenConfig);
const resultJson = await result.json();
const accessToken = await oauth2.accessToken.create(resultJson);
const accessTokenJson = await accessToken.json();
//if you need
this.setState({
accessTokenJson,
});
//For debugging
console.log('result', {resultJson, accessTokenJson});
}
答案 3 :(得分:0)
handleSubmit = async (e) => {
e.preventDefault();
console.log("form Submit ", this.state);
const { email, password } = this.state;
try {
const config = {
"content-type": "application/json",
};
this.setState({ loading: true });
const { data } = await axios.post(
"/api/users/login",
{
email,
password,
},
config
);
} catch (e) {
console.error("Error Login!", e);
this.setState({
error: e.response.data.message,
});
}
};