0

I'm getting a 405 (METHOD NOT ALLOWED) on a post request. I know that jsonp only works for GET requests, and that I most likely need to enable CORS. Is there a way to enable CORS through my javascript file? Or any way that doesn't involve creating a separate server side bridge? Here is the code for the ajax request:

function getData(){
    var myUrl = 'http://text-processing.com/api/sentiment/';
    var searchTerm = "happy";

    $.ajax({
        url: myUrl,
        type: 'POST',
        data: { 'text' : searchTerm },
        dataType: 'jsonP',
        error: function(msg) {
            console.log(msg);
        },
        success: function(response){
            console.log("it worked");
            console.log(response);
        }
     });
}
getData();
  • 3
    CORS has to be enabled in the server... you can't do much in client side.... see http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy – Arun P Johny Mar 02 '14 at 07:13

1 Answers1

0

if you are using ExpressJS There is a way that is to enable cross domain:

In the file you are posting for, after the requires statements, try to add this code here: exemplo: you are posting for user.js, so past it in the beginning of the file after you get the routes.

var router = express.Router();

router.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT, GET,POST,OPTIONS");
  next();
 });

Actually, you can add just:

  router.all('*', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      next();
     });

or this for specific requests:

 router.all('/', function(req, res, next) {
          res.header("Access-Control-Allow-Origin", "*");
          res.header("Access-Control-Allow-Headers", "X-Requested-With");
          next();
         });

However, I think this is not so secure. You can do a research like I am doing now to see the best way to use it, but you can use it for test and change it later. At least, you are not going to be stuck in this part.

source : http://enable-cors.org/server.html

http://enable-cors.org/server_expressjs.html

Good Luck! ;)

Andressa Pinheiro
  • 1,517
  • 2
  • 18
  • 28