Angular Using Wrong URL for querying MongoDB with NodeJS - node.js

I have this Angular 7 app that was working fine until I decided to move my logic out of the app.component.ts file into a new login.component.ts file. Ever since I did this, when I try and login and the app queries the database, it uses the wrong url--4200 instead of 3000. I set up a proxy.conf.json file like this:
{
"/api": {
"target": "http://localhost:3000",
"secure": false
}
}
This actually was already set up before I made the switch out of my app.component.ts file. I didn't make any other changes than reconnecting everything from the move to another component. I can't find where Angular is pointed to localhost:4200 instead of 3000. Does anyone have any ideas? Thanks in advance. Banging my head against the wall. By the by my OS is Windows 10 running VS Code.
Here's the error of my next issue:
VM623:37 ERROR TypeError: Cannot read property '0' of undefined
at
LoginComponent.push../src/app/login/login.component.ts.LoginComponent.toPrint
And here are the two functions involved with this error:
toPrint(match) {
return `Name: ${this.match[0].name} Checking: ${this.match[0].checking}
Savings: ${this.match[0].savings}`
}
printUserData(match){
this.buttonPressed = true;
return this.loginComponent.toPrint(match);
}

Just include your proxy configurations in angular.json file so that at the time when you run your application it run your proxy as well.
Example -
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "movie-analysis:build",
"proxyConfig": "src/proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "movie-analysis:build:production"
}
}
}
Hope it helps :)

Related

How to configure Vite to output single bundles for a Chrome DevTools Extension?

I am trying to create a Chrome DevTools Extension with Vite.
There are a couple different entry points. The main two are src/background.ts and devtools.html (which references src/devtools.ts).
There are is some code that I want to shared between them in src/devtools-shared.ts.
After running the build, the entry points still contain import statements. Why and how do I get rid of them so they are self-contained bundles (Ideally not IIFE, just good old top level scripts)?
Here is what I have got:
vite.config.js:
const { resolve } = require('path')
const { defineConfig } = require('vite')
module.exports = defineConfig({
resolve: {
alias: {
"root": resolve(__dirname),
"#": resolve(__dirname, "src")
}
},
esbuild: {
keepNames: true
},
build: {
rollupOptions: {
input: {
'background': "src/background.ts",
'content-script': "src/content-script.ts",
'devtools': "devtools.html",
'panel': "panel.html",
},
output: {
entryFileNames: chunkInfo => {
return `${chunkInfo.name}.js`
}
},
// No tree-shaking otherwise it removes functions from Content Scripts.
treeshake: false
},
// TODO: How do we configured ESBuild to keep functions?
minify: false
}
})
src/devtools-shared.ts:
export const name = 'devtools'
export interface Message {
tabId: number
}
src/background.ts:
import * as DevTools from './devtools-shared'
src/devtools.ts:
import * as DevTools from './devtools-shared'
And then in dist/background.js I still have:
import { n as name } from "./assets/devtools-shared.8a602051.js";
I have no idea what controls this. I thought there would not be any import statements.
Does the background.ts entry point need to be a lib or something?
For devtools.html is there some other option that controls this?
I know there is https://github.com/StarkShang/vite-plugin-chrome-extension but this doesn't work very well with Chrome DevTool Extensions. I prefer to configure Vite myself.
It turns out that this is not possible. Rollup enforces code-splitting when there are multiple entry-points. See https://github.com/rollup/rollup/issues/2756.
The only workaround that I can think of is to have multiple vite.config.js files such as:
vite.config.background.js
vite.config.content-script.js
vite.config.devtools.js
Then do something like this in package.json:
"scripts": {
"build": "npm-run-all clean build-background build-content-script build-devtools",
"build-background": "vite build -c vite.config.background.js",
"build-content-script": "vite build -c vite.config.content-script.js",
"build-devtools": "vite build -c vite.config.devtools.js",
"clean": "rm -rf dist"
},
This is not very efficient as it repeats a lot of work between each build but that's a Rollup problem.

React component bundle for consuming by browser and node (react hooks issue)

I have seriously headache because of this issue.
Source code - https://github.com/marekkobida/stackoverflow
UPDATE - without React hooks everything works...
Issue
I am trying to build a single bundle (react component) for browser and node via webpack bundler for SSR purposes. Node should swallow that bundle as described here:
const React = require("react");
const ReactDOMServer = require("react-dom/server");
const Test = require("./public/index.js").default; // ✅ React Component (works)
ReactDOMServer.renderToString(React.createElement(Test)); // Error
but an error appears:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
BUT browser version works. However after adding externals into webpack configuration, the node version works and browser does not.
React component file before bundling via webpack bundler
import React from "react";
import ReactDOM from "react-dom";
function Test() {
const [_, __] = React.useState(1);
return React.createElement("div", null, _); // ✅ <div>1</div> (works)
}
if (typeof window !== "undefined") { // because of UMD
ReactDOM.render(React.createElement(Test), document.getElementById("index")); // ✅ (works)
}
export default Test; // ✅
webpack configuration file
...
{
entry: "./index.js", // File described above
// The node version will work but the browser version will stop working after uncommenting the lines below
//
// externals: {
// react: 'react',
// 'react-dom': 'react-dom'
// },
mode: "development",
output: {
filename: "index.js",
globalObject: "this",
libraryTarget: "umd",
path: path.resolve("./public"),
publicPath: "",
},
},
...
BUT browser version works. However after adding externals into webpack configuration, the node version works and browser does not.
This maybe considered a workaround, but you could use two separate webpack configs, one for the node and the other for the browser version.
Edit:
Also for the node version not working: You're only have a require for ReactDOMServer, but not for ReactDom itself, maybe that is a problem, too.
I'm using this form, maybe give it a try:
externals: {
"react": {
"commonjs": "react",
"commonjs2": "react",
"amd": "react",
"root": "React"
},
"react-dom": {
"commonjs": "react-dom",
"commonjs2": "react-dom",
"amd": "react-dom",
"root": "ReactDom"
},
},

Cross origin error between angular cli and flask

first i post the user id and password from the UI(angular) to flask
public send_login(user){
console.log(user)
return
this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions)
.pipe(retry(1),catchError(this.
handleError))
}
next i received it from backend
backend error
all the operations are working properly but at console the cross origin error is raising
Error at UI console
the http option in Ui side is mentioned below
constructor(private http: HttpClient) { }
// Http Options
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': 'http://localhost:9000',
'Access-Control-Allow-Methods': "GET,POST,OPTIONS,DELETE,PUT",
'X-Requested-With': 'XMLHttpRequest',
'MyClientCert': '', // This is empty
'MyToken': ''
})
}
the cors declared at backend is metioned below
cors = CORS(app, resources={r"/login": {"origins": "*"}})
#app.route('/login', methods=['GET','POST'])
def loginForm():
json_data = ast.literal_eval(request.data.decode('utf-8'))
print('\n\n\n',json_data,'\n\n\n')
im not able to find were is the problem is raising
Note: cross origin arising in the time of login process other wise in the consecutive steps
add below code in your app.py
CORS(app, supports_credentials=True)
and from frontend use
{with-credentials :true}
it will enable the communication between the frontend and backend
To me it seems the call is not leaving the front end (at least in my experience it is like this), because the browsers are securing this.
Create a new file proxy.conf.json in src/ folder of your project.
{
"/backendApiUrl": { <--- This needs to reflect the server backend base path
"target": "http://localhost:9000", <-- this is the backend server name and port
"secure": false,
"logLevel": "debug" <--- optional, this will give some debug output
}
}
In the file angular.json (CLI configuration file), add the following proxyConfig option to the serve target:
"projectname": {
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json" <--- this is the important addition
},
Simply call ng serve to run the dev server using this proxy configuration.
You can read the section Proxying to a backend server in https://angular.io/guide/build
Hope this helps.

Understanding deploy url and base href

I'm developing an Angular app which I need to deploy on path
https://examplePath/AppSection/myApp
There is a server which redirect http://examplePath/AppSection to http://localhost:8080.
So, what I thinked to do is to set, in my Angular.json, the base href property like this:
"serve": {
[..]
"options": {
"host": "0.0.0.0",
"port": 8080,
"browserTarget": "myApp:build",
"baseHref": "/myApp/"
},
[...]
Doing this the app was accessible but all the calls to runtime.js, polyfill.js, main.js, etc... doesn't work because the browser tryed to find these file on
http://examplePath/myApp
Then I read about the deployUrl property so I set the angular.json like that:
"architect": {
"build": {
"builder": "#angular-devkit/build-angular:browser",
"options": {"deployUrl": "https://examplePath/AppSection/",
[...]
"serve": {
[..]
"options": {
"host": "0.0.0.0",
"port": 8080,
"browserTarget": "myApp:build",
"baseHref": "/myApp/"
},
[...]
This configuration works but with several issues and the browser usually remove AppSection/ from the url (I don't know why).
Then I edited my baseHref property adding AppSection/ and the result is:
"deployUrl": "https://examplePath/AppSection/"
"baseHref": "/AppSection/myApp/"
This configuration works but the browser has some problems with sockjs-node:
WebSocket connection to 'wss://examplePath/sockjs-node/570/wwadpefk/websocket' failed: Error during WebSocket handshake: Unexpected response code: 404 GET
https://examplePath/sockjs-node/570/00lb5fwe/eventsource 404 (Not Found) VM3475 sockjs.bundle.js:1
GET https://examplePath/sockjs-node/570/kqry21k3/htmlfile?c=_jp.a5d54nx 404 (Not Found)
Refused to display 'https://examplePath/sockjs-node/570/kqry21k3/htmlfile?c=_jp.a5d54nx' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'none'".
Honestly I do not understood what I should do to deploy on a specific path.

Eslint with node.js - Parsing error: Assigning to rvalue

I'm trying to use a JS linter for the first time and have chosen eslint to test some AWS Lambda functions written in NodeJS. I get an immediate error that has me stumped.
module.exports.replyGet = ( event, context, callback ) => {
Generates the following error
14:28 error Parsing error: Assigning to rvalue
My .eslintrc.js reads as follows:
module.exports = {
"rules": {
"no-console":0
},
"extends": "eslint:recommended"
};
Can anybody advise a novice on how best to fix the error?
Many thanks
Add this to your eslint config file
"env": {
"es6": true,
"node": true
}

Resources