POST AJAX request denied - CORS?

后端 未结 4 2021
迷失自我
迷失自我 2020-12-20 13:45

I have setup CORS on my node.js server on port 5000 as follows:

var app = express();

app.use(cors()); //normal CORS
app.options(\'*\', cors()); //preflight         


        
相关标签:
4条回答
  • 2020-12-20 14:20

    I've never used cors() so I can't speak to that piece. But you could manually allow cross origin resource sharing by setting up the node.js headers.

    Add This Pre-Route on All Requests

    app.route('*')
       .all(function(req, res, next) {
         res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
         res.header('Access-Control-Allow-Origin', '*');
         res.header('Access-Control-Allow-Headers', 'X-API-TOKEN, Content-Type, Authorization, Content-Length, X-Requested-Wit
    h');
       next();
    })
    

    This should work.

    0 讨论(0)
  • 2020-12-20 14:25

    CORS doesn't work using the file protocol because there is no server there to send back the requisite headers. Your solution of using a server is the only way to get CORS to work.

    0 讨论(0)
  • 2020-12-20 14:30

    This is the code I am using. It is located in my app.js file

    app.all("/*", function (req, res, next) {
    
      res.header("Access-Control-Allow-Origin", req.headers.origin);
      res.header("Access-Control-Allow-Credentials",true);
      res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type,Accept,X-Access-Token,X-Key,Authorization,X-Requested-With,Origin,Access-Control-Allow-Origin,Access-Control-Allow-Credentials');
      if (req.method === 'OPTIONS') {
        res.status(200).end();
      } else {
        next();
      }
    });
    
    0 讨论(0)
  • 2020-12-20 14:43

    I have a project that use cors.

    The node code used is just:

    const cors = require('cors');
    const express = require('express');
    const app = express();
    
    app.use(cors());
    
    /* Connect/other routes here */
    

    The jquery code look a litte different:

    $.post('http://localhost:5000/connect', {}).done( () => {
      // Request complete
    }).fail((jqXHR) => {
      // Request failed 
    });
    
    0 讨论(0)
提交回复
热议问题