【问题标题】:post request to Express.js api from another computer从另一台计算机向 Express.js api 发布请求
【发布时间】:2019-05-13 16:27:34
【问题描述】:

我有一个在 localhost:3000 上运行的服务器,当我尝试在浏览器中访问 localhost:3000 时,我将 app.js 设置为使用角度路由器
(例如:app.use('/', express.static(path.join(__dirname, '/dist/Client')));

当我向我的 api 发出发布请求时,我会这样做:

const headers = new Headers({
  'Content-Type': 'application/json'
});

const options = new RequestOptions({
   headers: headers
});

this.http.post('http://localhost:3000/api/someAction',{body},options)
.toPromise()
.then(//function)

到目前为止,一切都是正确的,但是我怎样才能使我的服务器可以从另一台计算机访问。例如,如果同一网络上的另一台计算机知道服务器的私有 IP 地址,我希望他能够在导航到例如 192.168.1.10:3000 时访问我的应用程序。现在我可以访问,但我所有的 http 请求都失败了,我有以下错误

Access to XMLHttpRequest at 'http://localhost:3000/api/someFunction' 
from origin 'http://192.168.1.10:3000' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: It does not 
have HTTP ok status.

在 app.js 我有以下内容:

app.use(function(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, DELETE, OPTIONS");
  next();
});

【问题讨论】:

    标签: node.js angular express


    【解决方案1】:

    这是您收到的 CORS 错误消息。

    您可以使用 Express CORS 中间件来允许从其他来源调用您的服务器。确保选择正确的选项以允许来自其他 PC 的呼叫。

    https://expressjs.com/en/resources/middleware/cors.html

    还要确保将 CORS 中间件放在应用程序定义的顶部。

    const app = express();
    app.use(cors({ origin: "*" })); // Do this first
    //... the rest of your routes and handlers and middlewares
    

    在您的本地机器上似乎一切正常,打开您的 Chrome 开发工具,并确保 OPTION 调用已成功完成,并且返回了正确的标头。

    最后,从安全角度来看,为您的生产环境尽可能删除或限制 CORS 选项。仅在开发和测试期间使用灵活的 CORS 策略。

    【讨论】:

      猜你喜欢
      • 2023-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多