Node.js
とExpress.js
を使用するREST APIがあります。私はAngular5
アプリケーションを使用してREST APIを使用しています。アンギュラアプリケーションからAPI呼び出しを行うに関しては、それがサービスを介して行われ、コードは次のとおりです。エクスプレスルートには常に空のボディがあります
auth.service.ts
次のように私のノードのapp.ts
で
login(email: string, password: string) {
return this.http.post(environment.baseUrl + '/api/v1/login', JSON.stringify({ email: email, password: password }))
.map((response: Response) => {
let user = response.json();
if (user && user.token) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
});
}
、アプリケーションが定義されます。
app.ts
:
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,__setXHR_');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.header('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
そして、あなたは、コントローラを見れば、ここでのコードは次のとおりです。
login = (req, res) => {
console.log(req.body);
this.model.findOne({ email: req.body.email }, (err, user) => {
if (!user) { return res.sendStatus(403); }
user.comparePassword(req.body.password, (error, isMatch) => {
if (!isMatch) { return res.sendStatus(403); }
const token = jwt.sign({ user: user }, process.env.SECRET_TOKEN); // , { expiresIn: 10 } seconds
res.status(200).json({ token: token });
});
});
}
私は403エラーを取得し、以下の私のコンソール上に印刷されているものです。
[2] {}
[2] {}
[2] POST /api/v1/login 403 22.004 ms - 9
私はかなり私のクロムデバッガに送信されるリクエストボディを見ることができます。
私はここで間違って何をしているのですか?
req.bodyには何がありますか? – pioro90
ログインコントローラのreq.body、user、isMatchの値に関するデバッグ情報をさらに提供してください。 – Ayan
'this.http.post'は約束を返しませんか? 'map'は' then'で置き換えられませんか? –