Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

Angular + Node.JS CORS Issue Resources not loading on local net PCs

39 views
Skip to first unread message

Matías Huartamendía

unread,
Jan 11, 2025, 3:37:15 AMJan 11
to Angular and AngularJS discussion

I am currently writing Angular as front end and node.js as backend application.

Phones and other network PCs do not load the resources all duue to CORS issue.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/news. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404

However I do have CORS in my code

const express = require('express');
const app = express();
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const sqlite3 = require('sqlite3').verbose();
const path = require('path'); // Required for serving static files
const PORT = process.env.PORT || 3000;

const cors = require('cors');

app.use(cors({
    origin: '*', // Allow both local and network access
    methods: 'GET,POST,PUT,DELETE,OPTIONS',
    allowedHeaders: 'Content-Type,Authorization',
    credentials: true // Allow cookies if necessary
  }));
 
   
app.options('*', cors());

// Middleware for parsing JSON
app.use(express.json());  

// For serving static assets like images
app.use('/assets', express.static(path.join(__dirname, 'assets'), {
setHeaders: (res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
  }
}));

Tong Phou

unread,
Jan 12, 2025, 3:15:26 AMJan 12
to ang...@googlegroups.com
My case is different.  I used dotnet backend and let the proxy handle the cors for me.  Here is my proxy configuration:
const { env } = require('process');

const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
    env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'https://localhost:7080';

const PROXY_CONFIG = [
  {
    context: [
      "/api",
      "/medias",
      "/Todo",
      "/MediaMetaData",
      "/Rpm",
      "/Pdf",
      "/Tube",
      "/updatedatabase"
    ],
    target,
    secure: false
  }
]

module.exports = PROXY_CONFIG;

on Angular side you don't need to put you url for example you code like this this.http.get('/api/getdate")
The proxy will handle the url for you by padding https://youwebsite/api/getdate both in live and dev environment (in dev it pads http://localhost:4200/api....

In dot net side there are codes in the program.cs but I don't think you need it since your env is different.  Let me knows if you need to see my program.cs
Happy new year.

--
You received this message because you are subscribed to the Google Groups "Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/angular/7dd0b86e-772a-4b49-9f75-7b7a18bf96acn%40googlegroups.com.

Tong Phou

unread,
Jan 12, 2025, 3:23:05 AMJan 12
to ang...@googlegroups.com
I use jwt to talk to dotnet on the backend.
here is my intercept code:
this.accountService.user$
  .pipe(take(1))
  .subscribe({
    next: user => {
      if (user) {
        // Clone from the coming request and add Authorization header to that
        request = request.clone({
          setHeaders: {
            Authorization: `Bearer ${user.jwt}`
          }
        });
      }
    }
  })
======
main.ts
bootstrapApplication(AppComponent, {
  providers: [
    provideAppInitializer((initializeFacebookSdk)()),
    importProvidersFrom(BrowserModule, BrowserAnimationsModule, AudioPlayerRoutingModule, AppRoutingModule, SharedModule, HomeModule, NgxSpinnerModule, NgxExtendedPdfViewerModule, FormsModule, MatDatepickerModule, MatNativeDateModule),
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JwtInterceptor,
      multi: true
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: LoadingInterceptor,
      multi: true
    },
    MessageService,
    provideHttpClient(),
    provideAnimationsAsync(),
    provideAnimations()
  ]
})

I think you intercept features to insert method, origin etc.

Thanks.
Reply all
Reply to author
Forward
0 new messages