当我通过Postman提出请求时,这不会发生;只有一个获得请求以正确的令牌到达后端。当我从Angular做到这一点时,请求点击两次。这样做的原因是什么?
从Angular提出的请求是这样的:
public async getAllIngredients(): Promise<Ingredient[]> {
try {
return await firstValueFrom(
this.http.get<Ingredient[]>(
`${environment.API_URL}/your-chef/ingredients/getIngredients`,
{
withCredentials: true,
}
)
);
} catch (error) {
throw error;
}
}
在后端(Node + Express)中,我有一个中间件,可以检查用户是否具有令牌:
const isAuthenticated = (
req: Request,
res: Response,
next: NextFunction
): void => {
try {
req.session = {};
// We exclude this routes, because otherwise a user would not be able to log in or register because they would not have a token.
const excludedRoutes: string[] = ["/user/login", "/user/register"];
if (excludedRoutes.includes(req.path)) {
return next();
}
console.log(req.method);
// We ignore when try to checkToken because data has been set on login
if (req.path !== "/user/checkToken") {
const data: JwtPayload | string = verifyToken(req.cookies.access_token);
req.session.user = data as IUserSession;
}
next();
} catch (error: any) {
if (error.code === ERRORS.USER.INVALID_TOKEN.code) {
res.status(error.status).send({ message: error.message });
} else {
res.status(500).send({ message: "Error when validate authentication" });
}
}
};
在后端,我有像这样配置的CORS和中间件:
app.use(
cors({
origin: process.env.FRONT_END_HOST,
credentials: true,
})
);
app.use(isAuthenticated);
The headers of the two GET requests are as follows: First get (wrogn):
{
"host": "localhost:3000",
"connection": "keep-alive",
"accept": "application/json, text/plain, */*",
"accept-language": "*",
"sec-fetch-mode": "cors",
"user-agent": "node",
"accept-encoding": "gzip, deflate"
}
Secong get (correct):
{
"host": "localhost:3000",
"connection": "keep-alive",
"sec-ch-ua-platform": "\"Windows\"",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36",
"accept": "application/json, text/plain, */*",
"sec-ch-ua": "\"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\", \"Google Chrome\";v=\"134\"",
"sec-ch-ua-mobile": "?0",
"origin": "http://localhost:4200",
"sec-fetch-site": "same-site",
"sec-fetch-mode": "cors",
"sec-fetch-dest": "empty",
"referer": "http://localhost:4200/",
"accept-encoding": "gzip, deflate, br, zstd",
"accept-language": "es,es-ES;q=0.9,ca;q=0.8,en;q=0.7",
"cookie": "access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2Nzc1N2YwZGZlYzMxZDgzMWE3OWQ2ZGQiLCJpYXQiOjE3NDE5NTIwMzAsImV4cCI6MTc0MTk1OTIzMH0.hrOWu0WwxX2d7zNqnv1XPeGKw9tAz6FHgcV1gIpQJ3Q",
"if-none-match": "W/\"128-RGyy7TUC0nG6pCSxdFRvDFMWJbo\""
}
另一个相关的细节可能是我称之为服务和getingRedients的地方,这是在此onInit中:
@Component({
selector: 'ingredients-page',
imports: [SearchInputComponent, TranslateModule, IngredientCardComponent],
templateUrl: './ingredients-page.component.html',
styleUrl: './ingredients-page.component.scss',
})
export class IngredientsPageComponent implements OnInit {
public ingredients: Ingredient[] = [];
/**
* Constructor to import all dependencies
*
* @param {IngredientService} ingredientService
*/
constructor(private ingredientService: IngredientService) {}
public async ngOnInit(): Promise<void> {
try {
console.log('entering the function');
this.ingredients = await this.ingredientService.getAllIngredients();
} catch (error) {
console.log('function error');
throw error;
}
}
}
错误仅出现在Angular服务器控制台中,而在浏览器中不出现。 Angular Dev客户端服务器控制台:
角dev客户端服务器控制台输出IMG浏览器控制台:浏览器控制台输出IMG
我认为此错误是在Angular的OnInit中,因为我尝试删除其内容并通过按钮使GetallingRedients调用,并且该错误未出现。 我尝试了所有可能的CORS配置,但没有任何作用。
错误是由于启用了Angular SSR引起的。为了修复它,我通过删除“服务器”:“ src/main.server.ts”并将输出模式从angular.json.json.json.jsh.json.ts.'s.json.ts.