当前,我正在尝试将Google Auth添加到React应用程序。我能够获取信息并将其发送到后端(RoR)。在后端,我将令牌发送回我的React前端,但我一直得到:Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0
。我已经坚持了一段时间,没有运气。也许你们可以帮忙。
我尝试使用Fetch
和Axios
发出ajax请求。我尝试过以不同的方式编写ajax请求,但是没有运气。我发现了类似的文章,但有类似的错误:Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
,但是我检查了我的网络标签,并且正确地获取了JSON,所以我真的不明白问题出在哪里。
以下是提取代码段:
googleResponse = async (info) => {
const data = {
first_name: info.w3.ofa,
last_name: info.w3.wea,
email: info.w3.U3,
picture: info.w3.Paa,
access_token: info.accessToken
}
const headers = new Headers()
headers.append('Content-Type', 'application/json')
const options = {
method: 'POST',
body: JSON.stringify(data),
headers
}
const response = await fetch('http://localhost:4000/auth', options)
const returnedData = await response.json()
returnedData.then(r => console.log(r)) // -> Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0
};
这是我的网络标签:
我将继续寻找,但是如果有人发现我做错了,那将是很大的帮助。
反应代码:
import React, { Component } from 'react';
import { GoogleLogin } from 'react-google-login';
import config from './config.json';
class App extends Component {
constructor() {
super();
this.state = { isAuthenticated: false, user: null, token:''};
}
logout = () => {
this.setState({isAuthenticated: false, token: '', user: null})
};
onFailure = (error) => {
alert(error);
};
googleResponse = async (info) => {
const data = {
first_name: info.w3.ofa,
last_name: info.w3.wea,
email: info.w3.U3,
picture: info.w3.Paa,
access_token: info.accessToken
}
const headers = new Headers()
headers.append('Content-Type', 'application/json')
const options = {
method: 'POST',
body: JSON.stringify(data),
headers
}
const response = await fetch('http://localhost:4000/auth', options)
const returnedData = await response.json()
returnedData.then(r => console.log(r)) // -> Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0
};
render() {
let content = !!this.state.isAuthenticated ?
(
<div>
<p>Authenticated</p>
<div>
{this.state.user.email}
</div>
<div>
<button onClick={this.logout} className="button">
Log out
</button>
</div>
</div>
) :
(
<div>
<GoogleLogin
clientId={config.GOOGLE_CLIENT_ID}
buttonText="Login"
onSuccess={this.googleResponse}
onFailure={this.onFailure}
/>
</div>
);
return (
<div className="App">
{content}
</div>
);
}
}
export default App;
RoR代码:
class UsersController < ApplicationController
protect_from_forgery with: :null_session
def auth
secret = 'pineapple'
@token = JWT.encode params["data"], secret, 'HS256'
render json: @token
end
end