我正在尝试为具有Express后端的React Client应用创建登录页面。
// Except from App.js in Client
async function performLogin (values) {
const { email:username,password } = values;
const credentials = { username,password };
const response = await fetch('http://localhost:4000/tokens/',{
method: 'POST',headers: new Headers({
'Content-Type': 'application/json','accept': 'application/text',}),body: JSON.stringify(credentials)
});
console.log('Result from backend token: '+JSON.stringify(response));
};
// tokens.js from backend
const jwt = require('jsonwebtoken');
const findUser = require('../lib/find-user');
const signature = process.env.SIGNATURE;
const expiresIn = process.env.EXPIRESIN;
const createToken = (user) =>
jwt.sign(
{ userId: user.id },signature,{ expiresIn: expiresIn }
);
// Code used to respond to /tokens/ path
let createTokenRoute = (req,res) => {
let credentials = req.body;
console.log('Credentials: '+JSON.stringify(credentials));
let user = findUser.byCredentials(credentials);
console.log('User: '+JSON.stringify(user));
if (user) {
let token = createToken(user);
res.status(201);
console.log('Token: '+JSON.stringify(token));
res.send(token);
} else {
res.sendStatus(422);
}
};
从Postman ping /tokens/
路径后,按预期方式,我得到了一个作为文本返回的令牌,后端的控制台忠实地吐出了:
Credentials: {"username":"rd@example.com","password":"12345678"}
User: {"id":"3","username":"rd@example.com","name":"Richard","password":"12345678"}
Token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c... etc."
邮递员向我展示了预期的结果:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c... etc.
但是,当从App.js
代码中调用时,后端的行为与以前一样,列出了凭据,用户和令牌...但是客户端的浏览器控制台给了我一个空对象:
Result from backend token: {}
我尝试使用accept
标头,但是我的无知让我看不出我要去哪里。我相当确定这完全是愚蠢的;-)
编辑:
所以我重写了performLogin
函数:
async function performLogin (values) {
const { email:username,body: JSON.stringify(credentials)
});
const result = await response.json();
console.log('Result from backend token: '+result);
};
现在页面崩溃了...
Unhandled Rejection (SyntaxError): The string did not match the expected pattern.
(anonymous function)
src/App.js:55
52 | }),53 | body: JSON.stringify(credentials)
54 | });
> 55 | const result = await response.json();
| ^ 56 | console.log('Result from backend token: '+result);
57 | };
58 |
View compiled