Angular $http.get call to web api - angularjs

I have two web applications running. App1 is an angular SPA and App2 is an MVC web api written in c#. I am executing both applications from Visual Studio 2015, running debug in IIS Express.
My angular code (App1) is trying to call an api controller in App2 using the following (debug) code:
$http.get('https://localhost:12345/api/values').then(function (response) {
alert(response.data);
}, function (err) {
alert(err);
}).catch(function (e) {
console.log("error", e);
throw e;
}) .finally(function () {
console.log("This finally block");
});
I always hit the "alert(err);" line - it never successfully executes and err has nothing useful in it to indicate what the problem could be.
In Postman (addin for Chrome), I can confirm the call I'm trying to make to App2 works fine. What am I doing wrong? Could this be an issue with CORS?
Thanks in advance!

You either experiencing CORS/SAME ORIGIN POLICY issue that some information about it in angular js can be found here: How to enable CORS in AngularJs.
this is how you handle it in server site in your case: http://docs.asp.net/projects/mvc/en/latest/security/cors-policy.html#cors-policy
or you better open the developer tools in console tab and bring us some more information about what happened in your code.

Ok the problem I had was in the web api (MVC 6 - ASP.net 5) in that I had to allow the requests from my angular web site. The startup.cs file had the following added:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddCors();
StartupInitialize(services);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseCors(builder => builder.WithOrigins("http://localhost:12345/"));
app.UseMvc();
antiForgery = (IAntiforgery)app.ApplicationServices.GetService(typeof(IAntiforgery));
}

Related

Deploy ASP.NET core 7 Web API with React front end

I wrote an ASP.NET Core 7 web API backend and standalone Javascript React front end. I can deploy the backend to IIS successfully and it works fine through postman. However when I try to deploy the react front end using the method described in this tutorial https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022
my visual studio just freaks out and crashes. I am trying to figure out how to deploy the front end manually without using the visual studio publish feature.
This is my project setup:
[1]: https://i.stack.imgur.com/cApdk.png
And this is the IIS side where the WEB API backend is currently published:
[2]: https://i.stack.imgur.com/GtJ9O.png
Do I need to create a separate site for the frontend or can I deploy it to the same site as the backend? How can I build the frontend and manually deploy to the IIS?
For the site to work properly, you should build the frontend part in production mode, i.e. use the command npm run build instead of npm run start.
And then move the resulting files to the wwwroot folder inside your NET7 project.
Additionally, you should add static files using the AddStaticFiles method.
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-7.0
Also remember to set the ports correctly, because you can have different ones in the development and production environment, you will do it in launchsetting.json
You just need to change your Program.cs file like below, the you could publish webapi project directly. Every step mentioned in the official document must be completed, and finally add the following code.
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
else
{
app.UseDefaultFiles();
//app.UseStaticFiles();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//app.MapControllers();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
// Add this line
endpoints.MapFallbackToFile("/index.html");
});
app.Run();
}
}
}
Test Result

Axios API request from React Native frontend to local spring backend service not working

I develop a React Native mobile app and for the backend I want to use Java Spring.
Now I have a standalone backend server running locally on port 8080 and my react native app is runned via Expo Go app with npm start.
For this question I have built a very simple example.
In the frontend application I want to do a GET request to retrieve a string back from the backend and I am using axios to send API requests.
The problem is that I get a Network Error error whenever I send the GET request to http://localhost:8080/
// dont bother func name
const loginUser = () => {
axios.get("http://localhost:8080/").then(value => {
console.log(value)
}).catch(err => {
console.log("REQUEST FAILED")
console.log(err)
})}
This is the handler when user presses a button axios request is send, Expected output: "Hello World"
output:
REQUEST FAILED
Network Error
at node_modules\axios\lib\core\createError.js:17:22 in createError
at node_modules\axios\lib\adapters\xhr.js:120:6 in handleError
at node_modules\event-target-shim\dist\event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:600:10 in setReadyState
at node_modules\react-native\Libraries\Network\XMLHttpRequest.js:395:6 in __didCompleteResponse
at node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:189:10 in emit
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
#RestController
//#CrossOrigin(origins = "*")
public class TestController {
#GetMapping("/")
public String hello(){
return "Hello World";
}
}
Simple Spring REST Controller
#SpringBootApplication
public class JpaApplication {
public static void main(String[] args) {
SpringApplication.run(JpaApplication.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET","POST","PUT","DELETE").allowedHeaders("*").allowedOrigins("*");
}
};
}
}
CORS Config just allowing all
I have tried putting the annotation #CrossOrigin(origins = "*") above the controller but it did not help (seen from: React and Axios : Axios Can't Access Java/SpringBoot REST Backend Service Because of CORS Policy). I have allowed all access from all locations in the CORS config but I get the same output. The example is very simple. I just want to get a simple string back and the solution is probably also very simple but after so many tries I can't come up with a solution. If I visit the URL on the browser I get the expected value, but via axios request it does not seem to work.
After some more searching I found it is not possible to send requests directly to localhost on a Android emulator, on IOS there is no problem. So the problem was after all on the React Native side.
So the fix was relatively easy and also found on stackoverflow, the following thread helped a lot: React Native Android Fetch failing on connection to local API.
I Installed ngrok and this generates a URL which I can use to temporary test my backend till I have hosted it.

Any Suggestions for getting ASP.NET Core + React Running on Elastic Beanstalk

I'm trying to get an ASP.NET Core with ReactJS application deployed to Amazon's Elastic Beanstalk. I've been using this tutorial to help me get started. I can deploy the tutorial (using the dotnet new web template) project just fine. However, when I publish a ASP.NET Core + React project (using dotnet new react template), I get the following exception when trying to access the application:
InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
Your application is running in Production mode, so make sure it has been published, or that you have built your SPA manually. Alternatively you may wish to switch to the Development environment.
This only occurs when I try to access ClientApp/ React components. When I access an API endpoint, there is no problem.
Additionally, this does not occur when running locally. Running locally works fine.
To reproduce this error, I've executed the following:
dotnet new react -o test-react/
dotnet publish test-react/ -o site/
cd site/
zip ../deploy.zip *
Finally, I manually import deploy.zip into AWS Elastic Beanstalk.
This is the Startup.cs file for that project.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
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.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
}
For reference, I am targeting .NET Core 3.1. Any ideas on how to solve this problem? I believe I've tried everything suggested on this GitHub issue. Any help would be greatly appreciated.
This question seems similar but is obviously for Angular and not React:
deploy Angular/Asp.Net Core 2.1 app to AWS: 500 error
It turns out that my deploy.zip package wasn't being created recursively so files in subdirectories were missing. Instead of doing,
zip ../deploy.zip *
I did,
zip -r ../deploy.zip *
which worked as intended. Silly me.

How to enable Cors in ASP.NET Web Api

I'm learning Angular 2. This is my service that's supposed to pull data from an ASP.NET Web api application.
#Injectable()
export class ExpenseService {
private _expUrl = "http://localhost:65400/api/expenses";
constructor(private _http: Http){}
getExpenses(): Observable<IExpense[]> {
return this._http.get(this._expUrl)
.map((response: Response) => <IExpense[]>response.json())
.do(data => console.log('ALL: ' + JSON.stringify(data)))
.catch(this.handleError)
}
//more here...
}
The above code is working fine in Microsoft Edge. However, in Chrome and FireFox, I'm getting the following error:
XMLHttpRequest cannot load http://localhost:65400/api/expenses.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:3000' is therefore not allowed
I've enabled CORS in my web api as suggested by many posts.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
//...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
//...
app.UseCors(builder =>
builder.WithOrigins("http://localhost:3000/"));
}
That didn't change the outcome. I'm still getting the same error in Chrome and FireFox while Edge is working just fine.
Thanks for helping
CORS is something that are enforced by the client, supported by the server.
CORS is there to help you as a user. It restrict the possibility for a client, like javascript on host google.com, to call a service on mydomain.com. This is a cross-domain call, which Chrome and FireFox does not allow. (Would assume that Edge also supported this). If you are hosting a service and client on some host and port, CORS is not used.
A service must define which host from a cross-domain is allowed. This can either be from all or from a specific host.
To allow access from all host do the following:
Configuration
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
Controller
[EnableCors("AllowSpecificOrigin")]
public class TestController : ApiController
If your service is a public service, be aware of the consequences.
You can read more here: https://learn.microsoft.com/en-us/aspnet/core/security/cors

CORS issue with Angular Client and ASP.NET Web API

I have a client side application built with AngularJS that is consuming services from a RESTful ASP.NET Web API. So far so good. I have created both of them under the same solution on Visual Studio, the API is an ASP.NET project and the AngularJS is a website. Both projects have to work using windows authorization so I created the API with windows authorization as the default AA mechanism in the project creator wizard, and for the AngularJS I have enable windows authentication on the properties tab of the project.
In order to test the communication between the two applications I decided to build a simple service. I created a Quotation model class, built the controller for it, and then added migrations and added some quotations in the database. I then tried to send a get request from the angular application only to receive this error:
After studying this issue I realized that I had to enable CORS on the web API. So I went to NuGet Package Manager and added the Microsoft.AspNet.Cors package to the project.
I then enabled CORS on the WebApiConfig.cs like this:
namespace Web_API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
And I added the header to my controller class and method (just in case on the class wasn't enough):
namespace Web_API.Controllers
{
[EnableCors("*", "*","*")]
public class QuotationsController : ApiController
{
private Web_APIContext db = new Web_APIContext();
// GET: api/Quotations
[EnableCors("*", "*", "*")]
public IQueryable<Quotation> GetQuotations()
{
return db.Quotations;
}
However, I still get the same error when I make a get request from the AngularJS application. Does anyone know how to fix this issue?
can you please try this:
[EnableCors(origins: "*", headers: "*", methods: "*")]
Also don't use EnableCors in your method. As you've used this on your controller, by default all methods will fall under this rule.
I hope this will solve your problem. Thanks.

Resources