Rails Responds with 404 on CORS Preflight Options Request

前端 未结 7 1337
既然无缘
既然无缘 2020-12-10 00:42

I\'m creating a set of services using Rails 4, which I am consuming with a JavaScript browser application. Cross-origin GETS are working fine, but my POSTs are failing the p

7条回答
  •  星月不相逢
    2020-12-10 01:04

    I'm not sure what javascript front end framework you are using (or if you are) since you didn't elaborate on what you are doing on the client-side to connect to your Rails 4 API, but I thought I'd add my answer in case it helps anybody.

    I ran into the exact same problem while connecting to a Rails 4 API with the Devise gem from an AngularJS front end (both were running on separate localhost ports). I was trying to log in to the back end using a POST request from an AngularJS form but I kept getting a 404 NOT FOUND error because I was sending an OPTIONS request with preflight. It took more than 2 days to figure out how to fix the problem.

    Basically you need to set up a proxy server for your front end (Angular, Backbone, whatever) in order to connect to your API so that your front end thinks that the request is using the same origin. There are some straightforward solutions out there for setting up Proxies using GruntJS. I am using Gulp for my project with Gulp-Connect and proxy-middleware with the following setup (based on the solution found here):

    var gulp            = require('gulp'),
        connect         = require('gulp-connect');
    
    gulp.task('devServer', function() {
          connect.server({
            root: './dist',
            fallback: './dist/index.html',
            port: 5000,
            livereload: true,
            middleware: function(connect, o) {
                return [ (function() {
                    var url = require('url');
                    var proxy = require('proxy-middleware');
                    var options = url.parse('http://localhost:3000/');
                    options.route = '/api';
                    return proxy(options);
                })() ];
            }
          });
        });
    

    I hope this helps someone!

提交回复
热议问题