【问题标题】:CORS issue with RestifyRestify 的 CORS 问题
【发布时间】:2019-06-09 18:33:36
【问题描述】:

我创建了一个带有使用 Restify 的 Node Api 的 ReactJs 应用程序,但是无论我做什么,我总是遇到 POST 方法的错误:

  • 405(方法不允许)
  • 从源“http://localhost:3000”获取“http://localhost:3001/api/login”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

我已经尝试了我在互联网上看到的所有内容,但我总是遇到这个问题。

要调用 API,这是我的代码:

const request = new Request(url + 'login', {
    method: 'POST',
    body: JSON.stringify({ 'username' : username, 'password' : password }),
    headers: new Headers({ 'Content-Type': 'application/json' })
})
return fetch(request)
    .then(response => {
        if (response.status < 200 || response.status >= 300) {
            throw new Error(response.statusText);
        }
        return response.json();
    })
    .then(({ token }) => {
        localStorage.setItem('token', token);
    });

我像这样配置 Restify:

const config = require('./config'),
  restify = require('restify'),
  errs = require('restify-errors');


var connection = config.db.get


const server = restify.createServer({
  name: config.name,
  version: config.version,
  url: config.hostname
});

server.use(restify.plugins.acceptParser(server.acceptable));
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());

server.use(
  function crossOrigin(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DELETE');
    res.header('Access-Control-Allow-Credentials', false);
    return next();
  }
);

server.listen(3001, function () {
  console.log('%s listening at %s', server.name, server.url);
});

server.post("/api/login", function (req, res) {
  res.send(200);
});

所以我希望在调用 Api 后收到验证(代码 200),但我总是遇到 CORS 问题。

还有什么要配置的吗?

感谢您的帮助!!! :D

【问题讨论】:

    标签: node.js reactjs rest restify


    【解决方案1】:

    您必须使用corsMiddleware 来避免cors 问题....将此代码写入您的 app.js 文件...应该可以正常工作

    var restify = require('restify');
    var corsMiddleware = require('restify-cors-middleware');
    
    var cors = corsMiddleware({
            preflightMaxAge: 5,
            origins: ['*'],
            allowHeaders:['X-App-Version'],
            exposeHeaders:[]
          });
    /**
     * Initialize Server
     */
     var server = restify.createServer();
    
    server.pre(cors.preflight);
    server.use(cors.actual);
    

    【讨论】:

    • 这在使用任何方法从外部恢复服务调用时都可以正常工作
    猜你喜欢
    • 2015-04-20
    • 2013-08-23
    • 2013-09-22
    • 2013-08-18
    • 2012-12-29
    • 2014-09-05
    • 2018-01-09
    • 2021-10-27
    相关资源
    最近更新 更多