【发布时间】:2019-04-08 12:45:40
【问题描述】:
我正在运行这段 NodeJS 代码并测试登录功能:
const express = require('express');
const bodyParser = require('body-parser');
let jwt = require('jsonwebtoken');
let config = require('./config');
let middleware = require('./middleware');
class HandlerGenerator {
login (req, res) {
let username = req.body.username;
let password = req.body.password;
// For the given username fetch user from DB
let mockedUsername = 'admin';
let mockedPassword = 'password';
if (username && password) {
if (username === mockedUsername && password === mockedPassword) {
let token = jwt.sign({username: username},
config.secret,
{ expiresIn: '24h' // expires in 24 hours });
// return the JWT token for the future API calls
res.json({
success: true,
message: 'Authentication successful!',
token: token
});
} else {
res.send(403).json({
success: false,
message: 'Incorrect username or password'
});
}
} else {
res.send(400).json({
success: false,
message: 'Authentication failed! Please check the request'
});
}
}
index (req, res) {
res.json({
success: true,
message: 'Index page'
});
}
}
// Starting point of the server
function main () {
let app = express(); // Export app for other routes to use
let handlers = new HandlerGenerator();
const port = process.env.PORT || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes & Handlers
app.post('/login', handlers.login);
app.get('/', middleware.checkToken, handlers.index);
app.listen(port, () => console.log(`Server is listening on port: ${port}`));
}
main();
问题是当我运行 POST 命令时:
curl --header "Content-Type: application/json" --request POST --data '{"password":"password", "username":"admin"}' http://localhost:8000/login
我收到错误:
SyntaxError: Unexpected token # in JSON at position 0
在 JSON.parse
对我来说,JSON 看起来格式很好。可能与编码有关?!我在哪里做错了? 谢谢。
【问题讨论】:
-
您的响应可能根本不是 Json。检查网络以查看您作为响应发送的内容,它可能是一些 html。
-
我不明白你的意思,对不起。问题出在请求上。
标签: node.js