简体   繁体   中英

Can't achieve CORS with Express.js

I'm making a PATCH request from a client running on localhost:3000 with the following code:

axios.patch(
  "http://localhost:3090/v1/users/etc/etc/etc", {
    name,
    url,
  }, {
    headers: {
      authorization: AUTH_TOKEN()
    }
  }
)

To a server configured as follows:

var app = express();
var cors = require('cors');
//etc

//var whitelist = [
//  'http://localhost:3000',
//  'localhost:3000'
//];
//passing this to cors() doesn't help
//var globalCorsOptions = {
//  origin: function(origin, callback) {
//    callback(null, whitelist.indexOf(origin) !== -1);
//  }
//};

app.use(morgan('combined'));
app.use(cors());
app.options('*', cors());
app.use(bodyParser.json({type:'*/*'}));

app.use('/v1', router);

var port = process.env.PORT || 3090;
var ip = process.env.IP || 'localhost';
var server = http.createServer(app);

server.listen(port, ip);

But the request just hangs. I can do POST/GET fine, but not DELETE/PATCH. The preflight happens fine but the actual request following just sits "stalled" indefinitely. Here's the headers for each request:

在此处输入图片说明 在此处输入图片说明

Sorry to ask this pretty standard question, but I've tried everything.

EDIT: Added the following to router (still not working):

var router = express.Router();

router.use(function(req, res, next) {
  res.header("Access-Control-Allow-Headers", "PATCH,DELETE,OPTIONS,GET,POST");
  next();
});

The actual error: 在此处输入图片说明

On the server you have to add following header to the response:

headers.Add("Access-Control-Allow-Headers", "PATCH,DELETE,GET,POST");

Actually all HTTP methods you want to allow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM