The server could not locate the desired response to the options provided

I have been working on a web API REST service in asp.net 5 and encountered an issue. The website is able to successfully send a request to the service, but when the service sends back the request options to the website, the response received says HTTP 1/1 404 Not Found.

Here is a Fiddler Screenshot of the "Options" request


The controllers for the service are configured by:

public class Startup {
        public void ConfigureServices (IServiceCollection services) {
        services.AddCors();
        services.AddMvc();
    }
}


One of the functions that the website needs to access is:

[Route("/operator")] // localhost:5000/operator
public class OperatorController : Controller
[EnableCors(origins:'*', headers>'*', methods:'*');
public IActionResult Index()
{
    return new HttpOkObject("Hello, select your operation");
}

The website accesses this function (by sending the route to the class which calls Index) using ajax

<script type="text/javascript">
    $(document).ready(function() {

        var options = {};
        options.url = "http://localhost:5000/installments";
        options.type = "GET";
        options.contentType = "application/jsonp";
        // options.dataType="jsonp";

        options.success = function (results) {
             alert(results.join);
        };

        options.error = function(evt){
            alert(evt.status + " - " + evt.statusText)
        };

        $.ajax(options);
    });
 </script>


[EDIT] To address the error, I added the following line:

<pre><code>app.Use(async (context, next) => {  context.Response.Headers.Append("Access-Control-Allow-Origin", "*"); await next(); });</code></pre>

This line was added before app.UseMvc();

While this adds the required header, it unfortunately resulted in the error message

“Response for preflight has invalid HTTP status code 404”

Answer №1

To ensure proper functionality, it is essential to specify the route and method for your function within the controller. One option is to establish a default mapping within the Startup class.

HttpConfiguration configuration = new HttpConfiguration();
        configuration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Alternatively, you can explicitly define the route in the function using the following tag:

[EnableCors(origins:'*', headers>'*', methods:'*');
[HttpGet]
[Route("printheads/")]
public IActionResilt Index()
{
    return new HttpOkObject("Hello, select your operation");
}

Answer №2

My solution to the issue was as follows:

Within Setup.cs, in

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

I included the following lines of code:


app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Origin", "*"); await next(); });
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Methods", "*"); await next(); });
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Max-Age", "3600"); await next(); });
app.Use(async (context, next) => { context.Response.Headers.Append("Access-Control-Allow-Headers", "*"); await next(); });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Yeoman - A guide for integrating an express server task into Gruntfile.js from the generator-angular template

Currently, I am diving into the world of Grunt and attempting to integrate an Express server into my AngularJS application that was initially created with Yoeman. I've made adjustments to the following task as shown below: grunt.registerTask('s ...

Differences between an AngularJS function() and a factory function() when used in a

When it comes to Angular, I've come across directives being written in two different ways: .directive('example', function () { // Implementation }); .directive('example', function factory() { // Implementation }) Can you ...

Automatically resize ui-select dropdown box to the left side

I've been tasked with incorporating AngularJS ui-select into my project, specifically creating a multiselect dropdown. Currently, the dropdown box automatically adjusts its width based on the length of the longest selectable text, causing it to extend ...

Develop a TypeScript class in a distinct file

I currently have ag-grid implemented in an Angular project with a CustomFilter. The problem is that the file containing the code for the CustomFilter function is becoming quite large and difficult to manage. I am now looking to move the CustomFilter to a s ...

Utilizing turbolinks enables the page to be reloaded upon form submission

Currently, I have implemented turbolinks in my Rails application. However, every time I submit a form, the page reloads and the form is submitted. Is there a way to prevent the page from reloading and also submit the form seamlessly? ...

Obtain the chosen item from a Bootstrap4 dropdown menu by utilizing a button

I am struggling to get a button with dropdown working in Bootstrap4. Below is the HTML code: <div class="row" id="dropdown-box"> <div class="col-lg-6"> <div class="input-group"> <div class="input-group-btn" id="button-grou ...

Error encountered: The module '@mui/x-data-grid' does not export 'GridActionsCellItem'

I'm facing an issue while trying to import 'GridActionsCellItem' from '@mui/x-data-grid'. Here's the code: import { GridActionsCellItem } from '@mui/x-data-grid'; An error message pops up indicating: Attempted impor ...

Marked checkboxes and Node.js

I'm having trouble grasping the concept of using HTML checkboxes with Node.js and Express. I have a basic form in EJS and before diving deeper into the backend logic, I want to ensure that the correct values are being retrieved. Despite my efforts to ...

Waiting for Promise Js to be fulfilled

I've been exploring the use of Bluebird for handling promises in Node.Js. I have encountered a situation where I need a function to return only when a promise is fulfilled. The desired behavior can be illustrated by the following code snippet: functi ...

Setting up language preferences without having to reload the entire page

Is there an alternative method to change the app language without refreshing the entire page? The code snippet below always refreshes the page, leading to a poor user experience. window.location.search = "sap-language=EN"; The following code snippet is a ...

Verifying the existence of a user in my mongodb database before adding a new user to avoid multiple registrations with the same email address

Attempted to use Express, I am in the process of creating a .js file that manages POST requests and checks whether a user already exists before adding them to my MongoDB database. I set up two separate MongoClient connections for different scenarios: one t ...

The express post request body fails to appear, rendering it empty

Server Side Code const express = require('express'); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended:true })); app.post('/',(req,res)=>{ console.log(req.body) }) Client Side Code const da ...

Tips on customizing the appearance of React rendering components

<div> <h3>{this.props.product.name}</h3> <h3>{this.props.product.code}</h3> {this.renderColors()} <article> <div da ...

Conversation with form component in angular2

I am currently using ng2-bootstrap-modal. For adding a sample form to the example Confirm Dialog, check out ng2-bootstrap-modal. To change the template: <div class="modal-dialog"> <div class="modal-content"> <form [formGroup]="login ...

`A collection of radio buttons within a repeating control`

I am working with a repeater control on my webpage. I want to include a radio button in each row (item template) and when one radio button is checked, the others should automatically be unchecked. How can I achieve this functionality? Any help or suggesti ...

Display or conceal toggle in ruby utilizing jQuery

I'm facing an issue with the functionality of a button that is meant to hide and show a form using jQuery. Initially, I added a path to signup in the button so that it would display and function properly. Now, when I click the button, the form shows u ...

How can I ensure that the 'popover' remains visible when hovering over both the anchorEl and the popover itself?

Check out this example of using material-ui at https://material-ui.com/utils/popover/#mouse-over-interaction Follow the steps outlined in the example above for material-ui at https://material-ui.com/utils/popover/#mouse-over-interaction When testing t ...

Tips for inserting characters at the cursor in a contenteditable element?

Is there a way to simulate typing a character in either JQuery or plain JavaScript? I am working with a contenteditable section where I need to intercept user input to replace certain characters (such as straight quotes with curly ones). While I have foun ...

Passing dependencies between controllers in ASP.NET MVC is a vital skill to master for

Hey there, I'm dealing with a bit of a dilemma: I have two controllers, A and B. My goal is to send an object from A to B, use some actions in B, and then return back to A. On top of that, I also want the ability to access B directly. My current data ...

Webpack fails to handle CSS background images

I'm having trouble with my Webpack configuration as it's not processing CSS images set in the background property: background: url('./hero.jpg') no-repeat right; This is resulting in an error message that reads: ERROR in ./src/app/comp ...