Angular9 http.get() doesn´t work properly - node.js

i'm developing a simple app to make consults to a backend on NodeJS. Everything works perfectly on localhost, but when i run the angular server on my ip adress (192.168.1.x) it dosen`t work anymore.
The nodeJS REST api it's running on 'http://localhost:3000/api/article' and the Angular server in https://192.168.1.x:4200.
The http.get code its this:
articles.component.ts:
import {ArticlesService} from '../../services/articles.service';
import {Article} from '../../models/article';
import { ViewChild } from '#angular/core'
#Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.scss'],
providers: [ArticlesService],
})
export class ArticlesComponent implements OnInit {
constructor(public articlesService: ArticlesService) { }
article: Article;
//Some other code that dosen't afect this
getArticle(id: String) {
this.articlesService.getArticle(id)
.subscribe( res => {
this.article = res as Article;
})
}
articles.service.ts:
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ArticlesService {
readonly API_URI = 'http://localhost:3000/api/article';
constructor(private http: HttpClient) {
}
getArticle(id: String) {
return this.http.get(this.API_URI+`/${id}`);
}
}
I`ve been trying some flags test and i realize that it never enter on the subscribe(), i'm new and it's the first time i run the server on my current ip and not in the localhost. So, i don't if maybe i can't request at the backend like that in this case or something else.
Using morgan and postman at the nodeJS REST api i see that the get request work properly on that side.
If someone could help me it would be awsome.

I exactly don't get you with the Angular server but all indicates that your Angular server doesn't have visibility of your localhost:3000. It's like when you deploy your spa in another server. That server doesnt know about your localhost and you have to replace your API_URI (using environments.ts) with the IP or domain name where your backend is:
For example i have this in my environment.prod.ts:
export const environment = {
production: true,
apiUrl: 'https://urltothenodejsbackend/api',
apiVersion: '/v1'
};

Related

Angular Universal app not honoring 'useAbsoluteUrl' or HTTP Interceptor on server-side

Our Angular 14 app is configured to use Angular Universal for SSR, and is integrated with our .NET 6 back end. The Universal guide incorrectly states (per this bug) that relative URLs will "automatically" be converted to absolute if you're using Express, but we still get relative URL errors from SSR even after updating our app.server.module.ts to include the necessary setting .useAbsoluteUrl = true (and providing the base URL), which fixes the issue for some per the bug thread:
export class AppServerModule {
constructor(
#Inject(INITIAL_CONFIG) private config: PlatformConfig,
private baseUrlService: BaseUrlService
) {
this.config.baseUrl = this.baseUrlService.getBaseUrl();
this.config.useAbsoluteUrl = true;
}
}
We've also tried implementing a custom HTTP Interceptor to handle the conversion, which doesn't seem to work either when declared as a provider in app.server.module.ts. This must be a misconfiguration issue, right? Our main.server.ts file imports the aspnet-prerendering package and has a default createServerRenderer() method, which calls renderModule(AppServerModule, options), but is something else missing with this approach? The main.server.ts is:
....
export default createServerRenderer(params => {
const { AppServerModule } = (module as any).exports;
const options = {
document: params.data.originalHtml,
url: params.url,
extraProviders: [
{ provide: APP_BASE_HREF, useValue: params.baseUrl },
{ provide: 'BASE_URL', useValue: params.origin }
]
};
// Bypass ssr api call cert warnings in development
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
const renderPromise = renderModule(AppServerModule, options);
return renderPromise.then(html => ({ html }));
});
export { renderModule } from '#angular/platform-server';
export { AppServerModule } from './app/app.server.module';
Microsoft's now-deprecated NodeServices implementation(?) apparently requires the use of commonjs for Node (in tsconfig.server.json), if that's relevant.

Unable to add an UI extension on Contentful. When i run nopm run start, I get a 404 error on ui_config

I am new to contentful. I am trying to develop an UI extension on Contentful using Contentful SDK.
I followed all the steps mentioned in this article.
This is the code I have in index.js.
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import { TextInput , Button } from '#contentful/forma-36-react-components';
import { init } from 'contentful-ui-extensions-sdk';
import '#contentful/forma-36-react-components/dist/styles.css';
import './index.css';
export class App extends React.Component {
static propTypes = {
sdk: PropTypes.object.isRequired
};
detachExternalChangeHandler = null;
constructor(props) {
super(props);
this.state = {
value: props.sdk.field.getValue() || ''
};
}
componentDidMount() {
this.props.sdk.window.startAutoResizer();
// Handler for external field value changes (e.g. when multiple authors are working on the same entry).
this.detachExternalChangeHandler = this.props.sdk.field.onValueChanged(this.onExternalChange);
}
componentWillUnmount() {
if (this.detachExternalChangeHandler) {
this.detachExternalChangeHandler();
}
}
onExternalChange = value => {
this.setState({ value });
};
onChange = e => {
const value = e.currentTarget.value;
this.setState({ value });
if (value) {
this.props.sdk.field.setValue(value);
} else {
this.props.sdk.field.removeValue();
}
};
onButtonClick = async () => {
console.log('hurray');
};
render() {
return (
<Button buttonType="primary" isFullWidth={false}
onClick={this.onButtonClick}>
Add Content from AEM DAM
</Button>
);
}
}
Ideally i am trying to create an UI extension to be used in contentful space. I downloaded the contentful SDK and i have put in a button. But I receive this error on the console and it doesn't work
Screenshot:
https://github.com/contentful/create-contentful-extension
Go to the content of this Content Type and enable mixed content at
your browser so that development version that is served from your
local machine could be rendered within https://app.contentful.com.
Better yet:
I'm not the biggest fan of disabling the mixed content setting in browsers. Can I use HTTPS in development mode?
Yes, you can serve your extension using HTTPS. Add --https to start command.
"start": "contentful-extension-scripts start --https",
It uses Parcel HTTPS under the hood , which generates a self-signed certificate, you might have to configure your browser to allow self-signed certificates for localhost.
I think that will fix the 404 error and get things working.
Please follow the readme carefully and post a separate question if you still have problems.

Open a URL in system default browser

I have an electron app using angular. I want to open a URL in the system default browser. I tried the code below
import { ElectronService } from 'ngx-electron';
export class AutoBackupsComponent implements OnInit {
constructor(private electronService: ElectronService) { }
private onAction() {
this.electronService.shell.openExternal('https:www.//google.com');
}
}
On the other threads, everyone suggested this way but it is not working for me. I am not sure how can I make it running in either renderer or main process.

How to split Nest.js microservices into separate projects?

Let's say I want to create a simplistic cinema-management platform. It needs few microservices: movies, cinemas, payments, etc.
How would you go about doing it in Nest.js? I don't want them in the same big folder as that feels like making a monolith. I want them to be separate Nest.js projects with their own git repositories so I can orchestrate them with Kubernetes later on.
How? How to connect from service cinemas to service movies if they are two separate projects and only share, let's say, Redis?
Edit:
This is not a question about microservices in general. This is a question Nest.js specific. I read the documentation, I know there are decorators like #Client for connecting to the transport layer. I just want to know where to use that decorator and maybe see a short snippet of code on "having two separate Nest.js repositories how to connect them together so they can talk to each other".
I don't care about the transport layer, that thing I can figure out myself. I just need some advice on the framework itself as I believe the documentation is lacking.
I got it working. Basically the way to do it is to create two separate projects. Let's say - one is a createMicroservice and another is just an HTTP app (but could easily be another microservice). I used a "normal" app just so I can call it easily for testing.
Here is the main.ts file that creates microservice.
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '#nestjs/common/enums/transport.enum';
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.REDIS,
options: {
url: 'redis://localhost:6379',
},
});
await app.listen(() => console.log('MoviesService is running.'));
}
bootstrap();
And one of the controllers:
#Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
#MessagePattern({ cmd: 'LIST_MOVIES' })
listMovies(): string[] {
return ['Pulp Fiction', 'Blade Runner', 'Hatred'];
}
}
Now - in the microservice you declare to what kinds of events should controllers react to (#MessagePattern). While in the "normal" service you do this in the controller when you want to ask other microservices for something (the main.ts is the simplest example that you get when you create a new project using #nestjs/cli.
The controller code:
#Controller()
export class AppController {
private readonly client: ClientProxy;
constructor(private readonly appService: AppService) {
this.client = ClientProxyFactory.create({
transport: Transport.REDIS,
options: {
url: 'redis://localhost:6379',
},
});
}
#Get()
listMovies() {
const pattern = { cmd: 'LIST_MOVIES' };
return this.client.send<string[]>(pattern, []);
}
}
So as long a client is connected to the same transport layer as the microservice - they can talk to each other by using the #MessagePattern.
For nicer code you can move the this.client part from a constructor to a provider and then use dependency injection by declaring the provider in the module.

Angular Universal server rendering WebSocket

Are there any examples of Angular Universal with WebSockets?
Serverside rendering does not know wat a WebSocket object is in my case. And if I use socket.io the node server hangs when trying to make a connections.
Some additional information about the problem:
I downloaded angular-universal-starter from github: https://github.com/angular/universal-starter
Which works fine out of the box running 'npm install' and 'npm start'
But after i added the following code to AppComponent
export class AppComponent implements OnInit {
ngOnInit() {
let webSocket = new WebSocket("----server url----")
}
}
I got the following error in my NodeJs server console:
EXCEPTION: WebSocket is not defined
ORIGINAL STACKTRACE:
ReferenceError: WebSocket is not defined
at AppComponent.ngOnInit (/Volumes/Development/cacadu/website/universal-starter-master2/dist
/server/index.js:41725:29)
Try only calling the websocket on the Client, for example you can detect whether it's the browser or the server with these imports
import { isPlatformBrowser } from '#angular/common';
import { Inject, PLATFORM_ID } from '#angular/core';
Then use them inside your code, this might be able to fix the problem!
#Component({ ... })
export class AppComponent implements OnInit {
private isBrowser: boolean = isPlatformBrowser(this.platformId);
constructor(
#Inject(PLATFORM_ID) private platformId: Object
) {
if (isBrowser) {
let webSocket = new WebSocket("----server url----");
}
}
}

Resources