Cross origin error between angular cli and flask - python-3.x

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.

Related

Net7 JWT Null Reference when publishing Blazor WASM Project?

so I've been working in the Net7 preview and have been trying to deploy a WASM project with identity and authentication which works fine locally. When I deploy the website 500s and digging into some of the logs, I get:
2022-11-07T13:42:28.854805951Z fail: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[3]
2022-11-07T13:42:28.854856853Z Exception occurred while processing message.
2022-11-07T13:42:28.854865053Z System.NullReferenceException: Object reference not set to an instance of an object.
2022-11-07T13:42:28.856255318Z at Microsoft.AspNetCore.ApiAuthorization.IdentityServer.IdentityServerJwtBearerOptionsConfiguration.ResolveAuthorityAndKeysAsync(MessageReceivedContext messageReceivedContext)
2022-11-07T13:42:28.856286120Z at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
In my Program.cs I have
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
builder.Services.AddAuthentication()
.AddIdentityServerJwt()
.AddJwtBearer()
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
I've been trying to follow different Duende guides but even when I eventually get it to run locally, I still get the same error. I've tried removing the JWT lines in AddAuthentication() and that also did not seem to help.
You need to have on your appsettings.json
"IdentityServer": {
"Key": {
"Type": "Development"
} },
Change the type to the correct one.

Weird behaviour of the fetch when running npm install

My setup is very simple and small:
C:\temp\npm [master]> tree /f
Folder PATH listing for volume OSDisk
Volume serial number is F6C4-7BEF
C:.
│ .gitignore
│ 1.js
│ package.json
│
└───.vscode
launch.json
C:\temp\npm [master]> cat .\package.json
{
"name": "node-modules",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"emitter": "http://github.com/component/emitter/archive/1.0.1.tar.gz",
"global": "https://github.com/component/global/archive/v2.0.1.tar.gz"
},
"author": "",
"license": "ISC"
}
C:\temp\npm [master]> npm config list
; cli configs
metrics-registry = "https://registry.npmjs.org/"
scope = ""
user-agent = "npm/6.14.12 node/v14.16.1 win32 x64"
; userconfig C:\Users\p11f70f\.npmrc
https-proxy = "http://127.0.0.1:8888/"
proxy = "http://127.0.0.1:8888/"
strict-ssl = false
; builtin config undefined
prefix = "C:\\Users\\p11f70f\\AppData\\Roaming\\npm"
; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\temp\npm
; HOME = C:\Users\p11f70f
; "npm config ls -l" to show all defaults.
C:\temp\npm [master]>
Notes:
The proxy addresses correspond to Fiddler.
Notice that the emitter dependency url uses http whereas the global uses https.
When I run npm install it starts and then hangs very quickly. And I know why, because Fiddler tells me:
The request is:
GET http://github.com:80/component/emitter/archive/1.0.1.tar.gz HTTP/1.1
connection: keep-alive
user-agent: npm/6.14.12 node/v14.16.1 win32 x64
npm-in-ci: false
npm-scope:
npm-session: 74727385b32ebcbf
referer: install
pacote-req-type: tarball
pacote-pkg-id: registry:undefined#http://github.com/component/emitter/archive/1.0.1.tar.gz
accept: */*
accept-encoding: gzip,deflate
Host: github.com:80
And the response is:
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Location: https://github.com:80/component/emitter/archive/1.0.1.tar.gz
Now this is BS, pardon my French, because the returned Location value of https://github.com:80/component/emitter/archive/1.0.1.tar.gz is invalid. But I suppose the server is not very smart - it just redirects to https without changing anything else, including the port, which remains 80 - good for http, wrong for https. This explains the hanging - the fetch API used by npm seems to retry at progressively longer delays which creates an illusion of hanging.
Debugging npm brings me to the following code inside C:\Program Files\nodejs\node_modules\npm\node_modules\npm-registry-fetch\index.js:
return opts.Promise.resolve(body).then(body => fetch(uri, {
agent: opts.agent,
algorithms: opts.algorithms,
body,
cache: getCacheMode(opts),
cacheManager: opts.cache,
ca: opts.ca,
cert: opts.cert,
headers,
integrity: opts.integrity,
key: opts.key,
localAddress: opts['local-address'],
maxSockets: opts.maxsockets,
memoize: opts.memoize,
method: opts.method || 'GET',
noProxy: opts['no-proxy'] || opts.noproxy,
Promise: opts.Promise,
proxy: opts['https-proxy'] || opts.proxy,
referer: opts.refer,
retry: opts.retry != null ? opts.retry : {
retries: opts['fetch-retries'],
factor: opts['fetch-retry-factor'],
minTimeout: opts['fetch-retry-mintimeout'],
maxTimeout: opts['fetch-retry-maxtimeout']
},
strictSSL: !!opts['strict-ssl'],
timeout: opts.timeout
}).then(res => checkResponse(
opts.method || 'GET', res, registry, startTime, opts
)))
And when I stop at the right moment, this boils down to the following values:
uri
'http://github.com/component/emitter/archive/1.0.1.tar.gz'
agent:undefined
algorithms:['sha1']
body:undefined
ca:null
cache:'default'
cacheManager:'C:\\Users\\p11f70f\\AppData\\Roaming\\npm-cache\\_cacache'
cert:null
headers:{
npm-in-ci:false
npm-scope:''
npm-session:'413f9b25525c452a'
pacote-pkg-id:'registry:undefined#http://github.com/component/emitter/archive/1.0.1.tar.gz'
pacote-req-type:'tarball'
referer:'install'
user-agent:'npm/6.14.12 node/v14.16.1 win32 x64'
}
integrity:undefined
key:null
localAddress:undefined
maxSockets:50
method:'GET'
noProxy:null
proxy:'http://127.0.0.1:8888/'
referer:'install'
retry:{retries: 2, factor: 10, minTimeout: 10000, maxTimeout: 60000}
strictSSL:false
timeout:0
I have omitted two values and I truly do not know their significance - opt.Promise and memoize. It is possible that they are crucial, I do not know.
Anyway, when I step over this statement, the aforementioned session appears in Fiddler with the bogus url of http://github.com:80/component/emitter/archive/1.0.1.tar.gz and I do not understand - how come? The debugger clearly shows that the uri parameter passed to fetch does not specify the port number.
I thought maybe it is some kind of a non string type, but typeof uri returns 'string'.
I have even written a tiny reproduction to execute just this request using the same arguments, except for the opt.Promise and memoize:
const fetch = require('make-fetch-happen')
fetch('http://github.com/component/emitter/archive/1.0.1.tar.gz', {
algorithms: ['sha1'],
cache: 'default',
cacheManager: 'C:\\Users\\p11f70f\\AppData\\Roaming\\npm-cache\\_cacache',
headers:{
"npm-in-ci":false,
"npm-scope":"",
"npm-session":"00b5bb97075e3c35",
"user-agent":"npm/6.14.12 node/v14.16.1 win32 x64",
"referer":"install",
"pacote-req-type":"tarball",
"pacote-pkg-id":"registry:undefined#http://github.com/component/emitter/archive/1.0.1.tar.gz"
},
maxSockets: 50,
method: 'GET',
proxy: 'http://127.0.0.1:8888',
referer: 'install',
retry: {
retries: 2,
factor: 10,
minTimeout: 10000,
maxTimeout: 60000
},
strictSSL: false,
timeout: 0
}).then(res => console.log(res))
But it shows up correctly in Fiddler - no port is added and hence the redirection works fine.
When there is no Fiddler (and hence no proxy) everything works correctly too, but I am very much curious to know why it does not work with Fiddler.
What is going on here?

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"
},
},

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.

Angular Using Wrong URL for querying MongoDB with NodeJS

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 :)

Resources