1

这是我的 index.js 文件。

import "babel-polyfill";
import http from "http";
import express from "express";
import cors from "cors";
import bodyParser from "body-parser";
import middleware from "./middleware";
import create from "./api/create";
import envVariables from "./envVariables";
import db from "./db";

let app = express();
app.server = http.createServer(app);

// 3rd party middleware
app.use(
  cors({
    exposedHeaders: envVariables.corsHeaders
  })
);

app.use(
  bodyParser.json({
    limit: envVariables.bodyLimit
  })
);

app.use(middleware({ envVariables, db }));

// api router
app.use("/api/create", create({ envVariables, db }));

//error handling
app.use((err, req, res, next) => {
  res.status(400).json(err);
});

app.server.listen(process.env.PORT || envVariables.SERVER_PORT, () => {
  console.log(`Started on port ${app.server.address().port}`);
});

export default app;

在调用“api/create”路由之前,我希望调用一个中间件,我必须在其中验证我的密钥。下面是我的中间件 index.js

    const axios = require('axios');
    import { Router } from 'express';

     const getData = async() => {
    try {
         return axios.post(`https://ilp-ulamp/api/fetchToken`).then(response => {
            return response.data;             
        }).catch(error => {
          console.log(error)
        })          

      } catch (error) {
        console.log(error);

      }
}

export default ({ config, db }) => {
    let routes = Router();

    let validateKey = async function(req, res, next) {      
        if(!req.body.authToken) 
        return res.status(401).send("Access denied. No token provided.");
        else {
            const resp = await getData();
            if(resp.length === 0){
                   return res.status(403).send("Access denied");
                }
             else {
                 next();
                    }    
        }
    }
    return validateKey;
}

https://ilp-ulamp/api/fetchToken在这里,问题是,调用端点时我没有得到正确的响应。我检查了 Postman,这个 API 给出了正确的响应,但是在中间件中调用它时,它给出的响应是空的。

我不确定我做得是否正确。

请帮我解决这个问题。

提前致谢!!

4

0 回答 0