简体   繁体   中英

503 Service Unavailable response. How can I use Heroku to relay API's using server-side code?

Hi after reading about safe ways to store api keys, I've decided to build my own api relay deployed to heroku using goodreads api as an example. Currently getting this below message from client-side: error from console

and below is my code:

const express = require("express");
const fetch = require("node-fetch");
const parseString = require('xml2js').parseString;
const rateLimit = require("express-rate-limit");
const app = express();
const cors = require('cors');
const port = process.env.PORT || 5000;

app.use(cors());

app.set('trust proxy', 1);

const limiter = rateLimit({
  windowMs: 1000, // 1 second
  max: 1, // limit each IP to 1 requests per windowMs
});

app.use(limiter);

app.get("/", (req, res) => res.send("Hello World!"));

app.post("/api/:search", (req, res) => {
   const searchString = `q=${req.query.q}`;
   res.setHeader("Access-Control-Allow-Origin", "*");
   res.setHeader("Access-Control-Allow-Credentials", "true");
   res.setHeader("Access-Control-Allow-Methods", "OPTIONS,POST,GET");
   (async function fetchGoodReads() {
      const response = await fetch(
        `https://www.goodreads.com/search.xml?key=${process.env.GOODREADS_API_KEY}&${searchString}`
     );
     var xml = await response.text();
     parseString(xml, (err, result)=> res.send(result.GoodreadsResponse.search));
   })();
 });

 app.listen(port, () => console.log(`Relay app listening on port ${port}!`));

I've also tried on postman, the response I get is the error page from heroku. Any help is welcome:)

I had to set my process.env variable on heroku then it worked fine. Here is where I found how to do that

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