405 status code returned for CORS request

Hello everyone, I need assistance with my CORS issue. I am trying to make an API request from another domain and encountering an error with the following code:

 var headers = {
        host: host,
        path: url + instance + '?action=reset',
        method: 'POST'
    };


var request = https.request(headers, function (response) {
    logger('OCICompute', 'reset', 'INSTANCE', 'Got response from OPCAPI:' + response.statusCode);

    res.header("Access-Control-Allow-Origin", "http://localhost:3000"); 
        res.header("Access-Control-Allow-Methods", "OPTIONS, TRACE, GET, HEAD, POST, PUT");
        res.header("Access-Control-Expose-Headers", "Origin, Content-Type, Authorization, Accept, X-Requested-With");
        res.header("Access-Control-Allow-Credentials", "true");
        res.header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, Accept, X-Requested-With"); 


    if (response.statusCode === 200) {
        response.on('data', function (body) {
            var data = JSON.parse(body);
            res.json(data);
        });
    } else {
        logger('OCICompute', 'reset', 'ERROR', 'stop fail');
        res.json({'result': 'Fail'});
    }
});

The code above is in my module.

In my main, I have an option:

app.opts('/\.*/', function(req, res, next){
  res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header("Access-Control-Allow-Methods", "OPTIONS, TRACE, GET, HEAD, POST, PUT");
  res.header("Access-Control-Expose-Headers", "Origin, Content-Type, Authorization, Accept, X-Requested-With");
  res.header("Access-Control-Allow-Credentials", "true");
  res.header("Access-Control-Allow-Headers", "Origin, Content-Type, Authorization, Accept, X-Requested-With");
res.send(200);

When I access this REST API, I encounter a 405 error - method not accepted and receive the following:

Host: api Url
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: */*
Accept-Language: ja,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:3000/?root=compute
Authorization: Bearer Token
Origin: http://localhost:3000
Connection: keep-alive

Allow: OPTIONS
Connection: keep-alive
Content-Length: 58
Content-Type: application/json
Date: Tue, 24 Apr 2018 02:05:47 GMT
Server: LBAAS
Strict-Transport-Security: max-age=31536000; includeSubdomains;
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block

I have another code that works as expected, the only difference being the use of GET method instead of POST.

 var headers = {
    host: host,
    path: url + instance + '?action=reset',
    method: **'GET'**
};

Here is the result of the GET method:

>

 Host: api Url User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:52.0)
> Gecko/20100101 Firefox/52.0 Accept: */* Accept-Language:
> ja,en-US;q=0.7,en;q=0.3 Accept-Encoding: gzip, deflate, br Referer:
> http://localhost:3000/?root=compute Authorization: Bearer Token
> Origin: http://localhost:3000 Connection: keep-alive
> 
> Access-Control-Allow-Credentials: true Access-Control-Allow-Headers:
> Content-Type, Authorization, Accept, X-Requested-With
> Access-Control-Allow-Methods: OPTIONS, TRACE, GET, HEAD, POST, PUT
> Access-Control-Allow-Origin: http://localhost:3000
> Access-Control-Expose-Headers: Content-Type, Authorization, Accept,
> X-Requested-With Connection: keep-alive Content-Length: 2556
> Content-Type: application/json Date: Tue, 24 Apr 2018 02:05:57 GMT
> Server: LBAAS Strict-Transport-Security: max-age=31536000;
> includeSubdomains; X-Content-Type-Options: nosniff X-XSS-Protection:
> 1; mode=block

Here is the code on the client side:

self.stopButtonClick = function (event) {
                    console.log("停止ボタンが押されました");
var headers = {"Authorization": 'Bearer ' + self.ociComputeToken._latestValue};              

                    $.ajax({
                        url: url,
                        type: "GET",
                        async: true,
                        headers: headers
                    }).done(function (data, textStatus, jqXHR) {
                        if (data.result !== 'Fail') {
                            self.compartmentHandler(self.compartmentId());
                        } else {
                            self.stopButtonClick(event);
                        }
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        console.log('サービスエラー');
                        self.stopButtonClick(event);
                    });
                };

Answer №1

After troubleshooting, I discovered the issue was due to an incorrect URL. However, I encountered a new problem of receiving a 502 bad gateway error. GET requests are functioning properly, but I'm unsure how to handle POST requests. Any suggestions on what steps to take 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

Prevent anchor link click and drag functionality on an HTML page / Swipe through a container containing links

Is there a way to prevent clicking and dragging on a link in a webpage? When you click the left mouse button on a link and drag it, you can unintentionally move the link or open a new tab. I am looking for a way to disable this behavior using JavaScript o ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

How can we automate the process of assigning the hash(#) in Angular?

Is it possible to automatically assign a unique hash(#) to elements inside an ngFor loop? <div *ngFor="let item of itemsArray; index as i"> <h3 #[item][i]> {{ item }} </h3> </div> I would like the outp ...

Move the text to the following line if a horizontal scroll bar is visible using JavaScript/JQuery and CSS styling

I have a section with multiple div elements...how can I ensure that when there is horizontal scrolling in the section, the hidden divs shift to the next line? HTML <section id="a"> <div class="num"> <div class="num"> <div class="num" ...

Child component in Angular fails to detect input changes

Hey there! I'm currently utilizing parent-child communication in my Angular project. In the parent component, I have an array that represents graph data. If you'd like to check out a demo of what I'm working on, feel free to click here. The ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...

Error encountered while attempting Ajax call in jQuery: "Uncaught TypeError: Cannot read property 'error' of null"

Having some trouble with my ajax call in jQuery. When I try to make the call, Chrome is giving me an error message saying "uncaught typeerror cannot read property 'error' of null." This prevents the class 'success' from being added. An ...

Javascript textfield button function malfunctioning

Here is the code I have created: HTML: <form method="post" id="myemailform" name="myemailform" action="form-to-email.php"> <div id="form_container"> <label class="descriptio ...

PHP regular expression /only match 10 whole digits/;

Currently, I am working on updating a PHP script that contains the following code snippet: function CheckNumber(MyNumber) { var MN = /^\d{10}$/; if (MN.test(MyNumber)) { return true; } return false; } The current script enfor ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

Issue with Ember Select not updating selection binding when populated by another Ember Select

New to Ember.js and grappling with the binding of selection in Select views to the controller. The template I am working with is as follows: {{view Ember.Select contentBinding="content" selectionBinding="selectedCompany" optionLabelPath="content.nam ...

Maintain the proportion of the browser window when reducing its size

<html> <head> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <img src="spacer--1200x800.png" width="1200" height="800" /> </body> </html> This section contains CSS ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

Combining Django's CSRF token with AngularJS

I currently have Django running on an Apache server with mod_wsgi, and an AngularJS app being served directly by Apache rather than through Django. My goal is to make POST calls to the Django server that is utilizing rest_framework, but I am encountering d ...

Exploring the distinctions among library, package, and module in JavaScript

As I dive into learning React, I find myself feeling overwhelmed by the idea of packages. Why can't we simply use a CDN link instead? There's this module that seems to be crucial but still puzzles me. And what exactly is npm and why is it necessa ...

Customized queries based on conditional routes - expressjs

Can we customize queries based on optional routes? app.get('/:category/:item?', function (req, res) { var category = req.params.category; var item = req.params.item; var sqlQuery = 'SELECT * FROM items WHERE category = ? AND item = ?&a ...

How can I change the background color of my notification box to red if the count is not equal to zero?

When the count equals 0, I don't want any effect on the notification box. However, when the count is not equal to zero, I want the notification box to turn red. I tried implementing this, but it's not working as expected. By not working, I mean n ...

Trigger an Ajax upload by clicking a different element than the upload button

Currently, I am using Ajax Upload to sequentially upload a maximum of 6 images. Each image has its own corresponding div in the layout, and I want the upload action to be initiated when I click on these divs. However, my attempt at achieving this functiona ...

Issues with non-functional plugins that utilize AJAX functionality

I am encountering an issue with my code that includes an ajax script for deleting a record, along with an animation during the deletion process. However, when I try to integrate the ajax script with plugins for confirmation, it seems to not be working prop ...