简体   繁体   English

我需要帮助向 nodejs express 服务器(Angular Universal)中的外部 API 发出 API 请求

[英]I need help making an API request to an external API in nodejs express server (Angular Universal)

I have an Angular Universal app.我有一个 Angular Universal 应用程序。 I am trying to access an external API, but doing it directly through the HttpClient generates a Cors error.我正在尝试访问外部 API,但直接通过 HttpClient 执行此操作会生成 Cors 错误。 In development, I successfully used a proxy to make the call.在开发中,我成功地使用了代理进行了调用。 I am trying to implement a proxy in production by creating a route on my express server that will swap in the appropriate external API route.我正在尝试通过在我的快速服务器上创建一个路由来实现生产中的代理,该路由将交换适当的外部 API 路由。 I am having trouble seeing anything online that can help with this particular situation.我无法在网上看到任何可以帮助解决这种特殊情况的内容。 I seem to have set up the route ok.我似乎已经设置好了路线。 I'm getting a 200 ok error but no data is being sent.我收到 200 ok 错误,但没有发送数据。 Can anyone help?任何人都可以帮忙吗?

server.ts服务器.ts

app.route('/api/book').get((req, res) => {

  https.get('https://api2.isbndb.com/book/' + req, (resp) => {
    let data = '';

    // A chunk of data has been recieved.
    resp.on('data', (chunk) => {
      data += chunk;
    });

    // The whole response has been received. Print out the result.
    resp.on('end', () => {
      res.send(res.json(data)
      );
    });

  }).on("error", (err) => {
    console.log("Error: " + err.message);
  });


});

控制台消息

You can simply enable cors from your server side like this.您可以像这样从服务器端简单地启用 cors。

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

For better understanding or to configure cors() url through.为了更好地理解或配置 cors() url。 can see here .可以在这里看到。

As by default it will call the options method to check the permission for the user to access that end points.默认情况下,它将调用 options 方法来检查用户访问该端点的权限。

or you can use below example from client side api call,或者您可以使用以下来自客户端 api 调用的示例,

let data = { name: 'Peter Parker', age: 34 };
 const results = await fetch(
  'http://localhost:3000/api/v1/results',
  {
    method: "post", 
    mode: "cors",
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*"
    },
    body: JSON.stringify(data)
  }
)
  .then(res => res.json()) 
  .then(res => {
    return res;
  })
  .catch(error => {
    error.response = {
      status: 0,
      statusText:
        "Cannot connect. Please make sure you are connected to internet."
    };
    throw error;
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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