我将博客作为一个分配,每个博客都有一个类似的按钮。当我点击这个按钮时,我会在后端添加一个类似的博客(用邮递员测试)。但是,它不起作用。如果我记录数据,我从后端返回到我的控制台,我收到一条错误,上面写着“没有提供令牌”#39;
这是我在控制台中获得的内容:
{succes: false, message: "No token provided"}
message: "No token provided"
succes: false
__proto__: Object
这是我的代码。
product.component.ts [likeProduct(id)]
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../../services/auth.service';
import { ProductService } from '../../services/product.service';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
messageClass;
message;
newProduct = false;
loading = false;
form;
processing;
username;
producten;
constructor(
private formBuilder: FormBuilder,
private authService: AuthService,
private productService: ProductService
) { }
createNewProductForm() {
this.form = this.formBuilder.group({
title: ['', Validators.compose([
Validators.required,
Validators.maxLength(50),
Validators.minLength(2),
this.alphaNumericValidation
])],
body: ['', Validators.compose([
Validators.required,
Validators.maxLength(500),
Validators.minLength(5)
])]
});
}
disableFormNewProductForm() {
this.form.get('title').disable();
this.form.get('body').disable();
}
enableFormNewProductForm() {
this.form.get('title').enable();
this.form.get('body').enable();
}
alphaNumericValidation(controls) {
const regExp = new RegExp(/^[a-zA-Z0-9 ]+$/);
if (regExp.test(controls.value)) {
return null;
} else {
return { 'alphaNumericValidation': true};
}
}
newProductForm() {
this.newProduct = true;
this.createNewProductForm();
}
reload() {
this.loading = true;
// Get producten
this.getAllProducts();
setTimeout(() => {
this.loading = false;
}, 4000);
}
comment() {}
onProductSubmit() {
this.processing = true;
this.disableFormNewProductForm();
const product = {
title: this.form.get('title').value,
body: this.form.get('body').value,
createdBy: this.username
};
this.productService.newProduct(product).subscribe(data => {
if (!data.succes) {
this.messageClass = 'alert alert-danger';
this.message = data.message;
this.processing = false;
this.enableFormNewProductForm();
} else {
this.messageClass = 'alert alert-success';
this.message = data.message;
this.getAllProducts();
setTimeout(() => {
this.newProduct = false;
this.processing = false;
this.message = false;
this.form.reset();
this.enableFormNewProductForm();
}, 2000);
}
});
}
goBack() {
window.location.reload();
}
getAllProducts() {
this.productService.getAllProducts().subscribe(data => {
this.producten = data.producten;
});
}
likeProduct(id) {
this.productService.likeProduct(id).subscribe(data => {
console.log(data);
this.getAllProducts();
});
}
ngOnInit() {
this.authService.getProfile().subscribe(profile => {
this.username = profile.user.username;
});
this.getAllProducts();
}
}
product.service.ts [likeProduct(id)]
import { Injectable } from '@angular/core';
import { AuthService } from './auth.service';
import { Http, Headers, RequestOptions } from '@angular/http';
@Injectable()
export class ProductService {
options;
domain = this.authService.domain;
constructor(
private authService: AuthService,
private http: Http
) { }
createAuthenticationHeaders() {
this.authService.loadToken();
this.options = new RequestOptions({
headers: new Headers({
'Content-Type': 'application/json',
'authorization': this.authService.authToken
})
});
console.log(this.authService.authToken);
}
newProduct(product) {
this.createAuthenticationHeaders();
return this.http.post(this.domain + 'producten/nieuwProduct', product, this.options).map(res => res.json());
}
getAllProducts() {
this.createAuthenticationHeaders();
return this.http.get(this.domain + 'producten/alleProducten', this.options).map(res => res.json());
}
getProductById(id) {
this.createAuthenticationHeaders();
return this.http.get(this.domain + 'producten/geefProduct/' + id, this.options).map(res => res.json());
}
editProduct(product) {
this.createAuthenticationHeaders();
return this.http.put(this.domain + 'producten/updateProduct', product, this.options).map(res => res.json());
}
deleteProduct(id) {
this.createAuthenticationHeaders();
return this.http.delete(this.domain + 'producten/verwijderProduct/' + id, this.options).map(res => res.json());
}
likeProduct(id) {
this.createAuthenticationHeaders();
return this.http.put(this.domain + 'producten/likeProduct/' + id, this.options).map(res => res.json());
}
}
producten.js [router.put(' / likeProduct',...]
const User = require('../models/user');
const Product = require('../models/product');
const jwt = require('jsonwebtoken');
const config = require('../config/database')
module.exports = (router) => {
router.post('/nieuwProduct', (req, res) => {
if (!req.body.title) {
res.json({ succes: false, message: 'Product titel is verplicht'});
} else {
if (!req.body.body) {
res.json({ succes: false, message: 'Product beschrijving is verplicht'});
} else {
if (!req.body.createdBy) {
res.json({ succes: false, message: 'Product creator is verplicht'});
} else {
const product = new Product({
title: req.body.title,
body: req.body.body,
createdBy: req.body.createdBy
});
product.save((err) => {
if (err) {
if (err.errors) {
if (err.errors.title) {
res.json({ succes: false, message: err.errors.title.message });
} else {
if (err.errors.body) {
res.json({ succes: false, message: err.errors.body.message });
} else {
res.json({ succes: false, message: err.errmsg });
}
}
} else {
res.json({ succes: false, message: err });
}
} else {
res.json({ succes: true, message: 'Product opgeslaan'});
}
});
}
}
}
});
router.get('/alleProducten', (req, res) => {
Product.find({}, (err, producten) => {
if (err) {
res.json({ succes: false, message: err });
} else {
if (!producten) {
res.json({ succes: false, message: 'Geen producten gevonden'});
} else {
res.json({ succes: true, producten: producten})
}
}
}).sort({ '_id': -1});
});
router.get('/geefProduct/:id', (req, res) => {
if(!req.params.id) {
res.json({ succes: false, message: 'Geen id opgeven'});
} else {
Product.findOne({ _id: req.params.id }, (err, product) => {
if (err) {
res.json({ succes: false, message: 'Geen geldige id' });
} else {
if (!product) {
res.json({ succes: false, message: 'Product niet gevonden' });
} else {
User.findOne({ _id: req.decoded.userId }, (err, user) => {
if (err) {
res.json({ succes: false, message: err });
} else {
if (!user) {
res.json({ succes: false, message: 'Geen authenticatie opgegeven'});
} else {
if (user.username !== product.createdBy) {
res.json({ succes: false, message: 'Geen geldige authenticatie'} );
} else {
res.json({ succes: true, product: product});
}
}
}
});
}
}
});
}
});
router.put('/updateProduct', (req, res) => {
if (!req.body._id) {
res.json({ succes: false, message: 'Geen id opgegeven'});
} else {
Product.findOne({ _id: req.body._id }, (err, product) => {
if (err) {
res.json({ succes: false, message: 'Geen geldig id'});
} else {
if (!product) {
res.json({ succes: false, message: 'Id is niet gevonden'});
} else {
User.findOne({ _id: req.decoded.userId }, (err, user) => {
if (err) {
res.json({ succes: false, message: err });
} else {
if (!user) {
res.json({ succes: false, message: 'Geen authenticatie opgegeven'});
} else {
if (user.username !== product.createdBy) {
res.json({ succes: false, message: 'Geen geldige authenticatie'} );
} else {
product.title = req.body.title;
product.body = req.body.body;
product.save((err) => {
if (err) {
res.json({ succes: false, message: err });
} else {
res.json({ succes: true, message: 'Product geüpdatet'});
}
});
}
}
}
});
}
}
});
}
});
router.delete('/verwijderProduct/:id', (req, res) => {
if (!req.params.id) {
res.json({ succes: false, message: 'Geen id opgegeven'});
} else {
Product.findOne({ _id: req.params.id }, (err, product) => {
if (err) {
res.json({ succes: false, message: 'Geen geldige id'});
} else {
if (!product) {
res.json({ succes: false, message: 'Product niet gevonden'});
} else {
User.findOne({ _id: req.decoded.userId }, (err, user) => {
if (err) {
res.json({ succes: false, message: err});
} else {
if (!user) {
res.json({ succes: false, message: 'Geen authenticatie opgegeven'});
} else {
if (user.username !== product.createdBy) {
res.json({ succes: false, message: 'Geen geldige authenticatie'});
} else {
product.remove((err) => {
if (err) {
res.json({ succes: false, message: err});
} else {
res.json({ succes: true, message: 'Product verwijdert'})
}
});
}
}
}
});
}
}
});
}
});
router.put('/likeProduct/:id', (req, res) => {
if(!req.body.id) {
res.json({ succes: false, message: 'Geen id opgegeven' });
} else {
Product.findOne({ _id: req.body.id }, (err, product) => {
if (err) {
res.json({ succes: false, message: 'Ongeldige id'});
} else {
if (!product) {
res.json({ succes: false, message: 'Product niet gevonden'});
} else {
User.findOne({ _id: req.decoded.userId }, (err, user) => {
if (err) {
res.json({ succes: false, message: 'Something went wrong.'});
} else {
if (!user) {
res.json({ succes: false, message: 'Geen geldige authenticatie'});
} else {
if (user.username === product.createdBy) {
res.json({ succes: false, message: 'Je kan je eigen post niet liken'});
} else {
if (product.likedBy.includes(user.username)) {
product.likes--;
const index = product.likedBy.indexOf(user.username);
product.likedBy.splice(index, 1);
} else {
product.likes++;
product.likedBy.push(user.username);
}
product.save((err) => {
if (err) {
res.json({ succes: false, message: err});
} else {
res.json({ succes: true, message: 'Blog geliket/disliket', product: product});
}
});
}
}
}
});
}
}
});
}
});
return router;
};
authentication.js [router.use ...]
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const config = require('../config/database')
module.exports = (router) => {
router.post('/register', (req, res) => {
if(!req.body.email) {
res.json({ succes: false, message: 'Je moet een email opgeven'});
} else {
if(!req.body.username) {
res.json({ succes: false, message: 'Je moet een gebruikersnaam opgeven'});
} else {
if(!req.body.password) {
res.json({ succes: false, message: 'Je moet een paswoord opgeven'});
}
else {
let user = new User({
email: req.body.email.toLowerCase(),
username: req.body.username.toLowerCase(),
password: req.body.password
});
user.save((err) => {
if(err) {
if(err.code === 11000)
res.json({ succes: false, message: 'Gebruikersnaam of email bestaat al' });
else {
if(err.errors) {
if(err.errors.email) {
res.json({ succes: false, message: err.errors.email.message})
} else {
if(err.errors.username) {
res.json({ succes: false, message: err.errors.username.message})
} else {
if(err.errors.password) {
res.json({ succes: false, message: err.errors.password.message})
} }
}
}
else {
res.json({ succes: false, message: 'Kan gebruiker niet registreren, Error: ', err });
}
}
} else {
res.json({ succes: true, message: 'Gebruiker geregistreerd'})
}
});
}
}
}
});
router.post('/login', (req, res) => {
if (!req.body.username) {
res.json({ succes: false, message: 'Je moet een gebruikersnaam opgeven'});
} else {
if (!req.body.password) {
res.json({ succes: false, message: 'Je moet een paswoord opgeven'});
} else {
User.findOne({ username: req.body.username.toLowerCase()}, (err, user) => {
if (err) {
res.json({ succes: false, message: err});
} else {
if (!user) {
res.json({ succes: false, message: 'Username niet gevonden'});
} else {
const validPassword = user.comparePassword(req.body.password);
if (!validPassword) {
res.json({ succes: false, message: 'Onjuist wachtwoord'});
} else {
const token = jwt.sign({ userId: user._id }, config.secret, {expiresIn: '24h'});
res.json({ succes: true, message: 'Succes!', token: token, user: { username: user.username }});
}
}
}
})
}
}
})
router.use((req, res, next) => {
const token = req.headers['authorization'];
if (!token) {
res.json({ succes: false, message: 'No token provided'});
} else {
jwt.verify(token, config.secret, (err, decoded) => {
if (err) {
res.json({ succes: false, message: 'Token ongeldig: ' + err});
} else {
req.decoded = decoded;
next();
}
});
}
});
router.get('/profile', (req, res) => {
User.findOne({ _id: req.decoded.userId }).select('username email').exec((err, user) => {
if (err) {
res.json({ succes: false, message: err});
} else {
if (!user) {
res.json({ succes: false, message: 'Username niet gevonden'});
} else {
res.json({ succes: true, user: user});
}
}
})
});
return router;
};
我的中间件在authentication.js中似乎有问题。它确实在其他情况下有效,所以我没有看到它。 有人看到了这个错误吗?感谢。