I have Cors Issues at my NodeJS Typescript Backend and Angular App with Vercel.
I want to send data from my node JS Server to my Angular App and retreive it there.
I have saw there a simmilar issues, but they are often not anweared or I have tried and did not work.
I use the latest NodeJS and Angular Version.
My vercel.json looks like this:
{
"version": 2,
"builds": [
{
"src": "./index.ts",
"use": "@vercel/node"
}
],
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Credentials", "value": "true" },
{ "key": "Access-Control-Allow-Origin", "value": "*" },
{
"key": "Access-Control-Allow-Methods",
"value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
},
{
"key": "Access-Control-Allow-Headers",
"value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
}
]
}
]
}
My Node JS:
const express = require('express');
const app = express();
// Route für GET-Anfragen an die Root-URL
app.get('/', (req, res) => {
res.send('Hello World');
});
const allowCors = fn => async (req, res) => {
res.setHeader('Access-Control-Allow-Credentials', true)
res.setHeader('Access-Control-Allow-Origin', '*')
// another common pattern
// res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT')
res.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
)
if (req.method === 'OPTIONS') {
res.status(200).end()
return
}
return await fn(req, res)
}
const handler = (req, res) => {
const d = new Date()
res.end(d.toString())
}
module.exports = allowCors(handler)
// Server auf Port 3000 starten
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
On my Angular App i have this:
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss'],
})
export class ChatComponent implements OnInit {
data: any[] = []; // Typisierung entsprechend den erwarteten Daten anpassen
private apiUrl = 'https://chat-backend-seven-tau.vercel.app/';
constructor(private http: HttpClient) { }
// Beispiel für einen GET-Request, um alle Chats abzurufen
getChats(): Observable<any[]> {
// Optional: Erstellen der HttpHeaders, wenn du spezielle Header benötigst
const headers = new HttpHeaders({
'Content-Type': 'application/json',
// Weitere Header können hier hinzugefügt werden, falls nötig
});
// Anfrage mit Headern, falls benötigt
return this.http.get<any[]>(`${this.apiUrl}`, { headers });
}
ngOnInit(): void {
this.getChats().subscribe(
(response) => {
this.data = response; // Daten in der Komponente speichern
console.log('Chats:', this.data);
},
(error) => {
console.error('Fehler beim Abrufen der Chats:', error);
}
);
}
}
I also restarted the Angular App again and it did not work.
How can I solve the issue? Thanks for any comment.
3
Need to do something like that
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// 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.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});```
7