Angular Using Random Url For Requests - angularjs

I'm trying to create a proxy for my angular application and my post request keeps getting sent to
http://www.gamersunite.com/users
even though i'm trying to post to
http://localhost:3000/api/users
At one point I had my proxy set as
{
"/api": {
"target": "http://url.com",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
but now it's currently
{
"/api": {
"target": "http://localhost:3000",
"secure": false,
"logLevel": "debug"
}
}
Why is it still redirecting to this random url?

Cleared the cache/cookies and now everything is working as expected

Related

Nx advanced reverse proxy configuration

Migrating a react application to an Nx integrated workspace, and having an issue with advanced proxy configuration.
I understand that for a simple proxy...
Specify the proxy.conf.json file
"serve": {
"executor": "#nrwl/webpack:dev-server",
"defaultConfiguration": "development",
"options": {
"verbose": true,
"buildTarget": "ydsca:build",
"hmr": true,
**"proxyConfig": "apps/ydsca/proxy.conf.json",**
"ssl": true,
"sslKey": "certs/localhost.key.pem",
"sslCert": "certs/localhost.crt.pem"
},
Implement the proxy.conf.json file, e.g....
{
"/caconnect/common/*": {
"target": "https://127.0.0.1:9443",
"secure": false,
"logLevel": "debug"
}
}
This works without any issues, however, the current React application uses "http-proxy-middleware" and a more advanced setupProxy.js file (wildcard matching such as "/**/common/" for any patch that contains /common/):
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
[
'/**/common/',
'/**/commonClassic/',
'/**/ydscaCommon/',
'/ymca',
'/staff'
],
createProxyMiddleware({
//Must use 127.0.0.1 as for some reason, localhost stopped working in node versions > 16
target: 'https://127.0.0.1:9443',
//Necessary for https with self signed certificates
secure: false,
changeOrigin: false,
//Additional logging stuff!
onProxyReq: function onProxyReq(proxyReq, req, res) {
// Log outbound request to remote target
console.log('--> ', req.method, req.path, '->', proxyReq.baseUrl + proxyReq.path);
},
onError: function onError(err, req, res) {
console.error(err);
res.status(500);
res.json({error: 'Error when connecting to remote server.'});
},
//logLevel: 'debug'
})
);
};
How can the same advanced proxying be configured in Nx?
Tried changing proxyConfig": "apps/ydsca/proxy.conf.json" to proxyConfig": "apps/ydsca/setupProxy.js", but it doesn't seem to like javascript files for proxy configuration!
Any suggestions?
Thank you.

How do I solve CORS Policy error with .NET 6 and React?

I am trying to call an API in the frontend, but I get this error instead:
Access to XMLHttpRequest at 'http://localhost:5087/api/GetPlayerById/2' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Frontend is running on http://localhost:3000/ (React)
Backend is running on http://localhost:5087/ (.NET 6)
API works on Postman
API works on browser (Copy/Pasting the API on browser)
CORS error appears when I call the API in React
I already looked at many post on CORS policy but none seems to help me. My last attemp was referring to Enable Cross-Origin Requests (CORS) in ASP.NET Core.
Code so far (in .NET 6):
Program.cs
using tournament_manager_backend.Data;
using Microsoft.EntityFrameworkCore;
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
policy =>
{
policy.WithOrigins("http://localhost:3000");
});
});
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddScoped<IPlayerRepository, PlayerRepository>();
builder.Services.AddScoped<IMatchRepository, MatchRepository>();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "server=(localdb)\\ProjectModels;database=TournamentManager"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Host": {
"CORS": "http://localhost:5087,http://localhost:3000"
}
}
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:19870",
"sslPort": 44328
}
},
"profiles": {
"tournament_manager_backend": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5087",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
}
}
}
}
I know there are a lot of questions on this topic already but I have already changed the code many times from different sources that if I were to refer them here, it will make this post too long. I did the best I can to give you as much details as possible so that I can seek effective guidance. I will appreciate anyone helping. Thanks!
The easiest solution is to include a proxy in the React server that you're using for development. In your package.json include:
"proxy": "http://localhost:5087/",
as part of the top level parameters (i.e., no parent). This creates a proxy through http://localhost:3000/ to your back end.
Note that this is for development. When you move to a "real" server you won't be using the React dev server for serving your front end code and there will likely be a different way to setup CORS.

SSE doen't work with vue-cli devServer proxy

I recently move from vue-cli 4.5.x to 5.0.x.
Since this upgrade it seems Server Sent Events (SSE) doesn't work any more with the WebPack Dev Server.
(I'm currently using vue-sse)
Note in production it works perfectly.
My devServer config looks like :
devServer: {
proxy: {
"/api": {
target: "http://localhost:8080",
ws: true,
changeOrigin: true,
},
},
},
It seems possible workarounds are :
Disable compression in the webpack devserver config.
Send Content-Type: no-transform in the response header.
(source : https://composed.blog/sse-webpack-dev-server)
I didn't test the 2. way but the 1. works for me.
devServer: {
proxy: {
"/api": {
target: "http://localhost:8080",
ws: true,
changeOrigin: true,
},
},
// To disable compression :
compress: false
},
If this doesn't help maybe you face this similar issue : https://forum.vuejs.org/t/server-sent-events-are-not-working-with-vue-cli-devserver-proxy-and-node-16-0/125450

CRA - how to proxy all requests but a specific one?

create-react-app docs says you can configure your proxy objects manually. I'm following the http-proxy-middleware docs on matching
to exclude a specific route but haven't got it to work.
Basically I'm serving my app from the /app route instead of root. So I want the following to happen:
/app/api proxies to http://localhost:3001, my backend service
All requests that does NOT start with /app proxy to http://cloud.my-app.com
This is what I've tried so far with no luck:
"homepage": "https://cloud.my-app.com/app",
"proxy": {
"/app/api": { // Works
"target": "http://localhost:3001"
},
"!/app/*": { // Does not work
"target": "https://cloud.my-app.com",
"secure": false
}
},
What am I missing?
Add the below as your proxy:
"proxy": {
"/app/api":{
"target":"http://localhost:3001",
},
"/.*/":{
"target":"https://cloud.my-app.com",
"secure":"false",
"changeOrigin": true
}
}

how to handle client side react routing in loopback.js

I am using react with loopback. I wanted to integrate react code in loopback.
if i do these 3 steps
1)middleware.json - put this
"files": {
"loopback#static": {
"params":"$!../client"
}
},`
2)root.js
router.get('/');
3)front end code
"build": "react-scripts build && cp -r build/* ../client/",
That didopen my react site on localhost:3000 .Now issue is when i do this
i cant access my loopback on :3000/explorer
So my first question is in this scenario, how to access explorer.
But then i rolled it back , because i wanted to use loopback explorer again.
So, i deleted all these added code and explorer came back
but when i added it again
Now, i dont see my react code
I can still see explorer at http://localhost:3000/explorer/
if i go to http://localhost:3000/apphome
i see 404 error
Right now, my middleware.json file for loopback is
{
"initial:before": {
"loopback#favicon": {}
},
"initial": {
"compression": {},
"cors": {
"params": {
"origin": true,
"credentials": true,
"maxAge": 86400
}
},
"helmet#xssFilter": {},
"helmet#frameguard": {
"params": [
"deny"
]
},
"helmet#hsts": {
"params": {
"maxAge": 0,
"includeSubdomains": true
}
},
"helmet#hidePoweredBy": {},
"helmet#ieNoOpen": {},
"helmet#noSniff": {},
"helmet#noCache": {
"enabled": false
}
},
"session": {},
"auth": {},
"parse": {
"body-parser#json": {},
"body-parser#urlencoded": {
"params": {
"extended": true
}
}
},
"routes": {
"loopback#rest": {
"paths": [
"${restApiRoot}"
]
}
},
"files": {
"loopback#static": {
"params":"$!../client"
}
},
"final": {
"loopback#urlNotFound": {},
"./LoopbackUrlNotFoundCatch.js": {}
},
"final:after": {
"strong-error-handler": {}
}
}
root.js file
'use strict';
//router.get('/', server.loopback.status());
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/');
server.use(router);
};
-edit
I made some changes. Now, i have react components showing, I can also see data when i use api routes. But, explorer is still missing.
middleware.json
"files": {
"loopback#static": [
{
"name": "publicPath",
"paths": ["/"],
"params": "$!../client"
},
{
"name": "reactRouter",
"paths": ["*"],
"params": "$!../client/index.html",
"optional":true
}
]
},
I have also changed named of root.js to root_something.js . In documentation, its written, no need of root.js
First of all you Should be create react app in an other director like
Root ->
|-- client // emply
|-- clint_src // react app
and getting build react app and copy build files to client
now you should be remove server.loopback.status() in "server/boot/root.js" file
Example:
router.get('/', server.loopback.status());
To :
module.exports = function(server) {
// Install a `/` route that returns server status
var router = server.loopback.Router();
router.get('/');
server.use(router);
};
after that you need say to loopback middleware which file should be load in your path
go to middlware /server/middleware.json and replace blow code to "files": {}
"files": {
"loopback#static": [
{
"paths": ["/"],
"params": "$!../client"
},
{
"paths": ["*"],
"params": "$!../client"
}
]
},
on "paths": ["*"], all route will be open react file exeption the "/api" and "explorer" so you should be handle page notfound inside react app
Hope This was help full
Good Luck
I suspect React's default service worker intercepts and tries to cache /explorer. It skips urls prefixed with __ so this might fix the need to clear browser:
In component-config.json:
{ "loopback-component-explorer": {
"mountPath": "/__explorer" }}
Then access explorer at /__explorer.
As the instructions for adding a GUI to a loopback application state, you need to remove the root.js '/' route completely, by either renaming the root.js file to something without a .js extension, or deleting the file altogether.
$ rm root.js
### or, you can do this
$ mv root.js root.js.old
In the loopback 3 server configuration, the client folder has to be setup as a middleware route in middleware.json, like so:
"files": {
"loopback#static": {
"params": "$!../client"
}
},
Now, your client application is served from the /client folder, and by default the static files are served with Express -- so, it will look for index.html when you hit localhost:3000/

Resources