Axios POST 不在 运行 内 NodeJS/Express 路由

Axios POST isn't running inside NodeJS/Express Route

我正在从另一个域 (domain1.com) 调用我的快速路由 (domain.com/api)。因此,我设置了 Express 以接受对路由 /api 的 POST 请求,并在通过 Axios 交换 JWT 以获取 Bearer 访问令牌之前签署 JWT。

我似乎无法启动 Axios post 请求。有没有可能是防火墙的问题?我怎样才能看到错误在哪里?请原谅,我对 Node/Express 还是个新手。

这是我的相关代码:

const express = require('express');
const cors = require("cors");
const jwt = require('jsonwebtoken');
const axios = require('axios');

// Initialize express app
var app = express();
var router = express.Router();

// Serve static pages
app.use(express.static('./'));

//init morgan logging
app.use(morgan("common"));

// parse JSON objects
app.use(express.json());

//init cors
app.use(cors({
    origin: ["My Request Domain Here"],
    methods: ["POST", "GET"],
    allowedHeaders: ["Content-Type", "Authorization"],
    credentials: true
}));

// Specify public page entry point
app.get('/', function(req, res) {
    res.sendFile(path.join('/index.html'))
});

app.post('/api', function(req, res){
 
 //get client data from Launch Request
 const oi = atob(req.body.oi);
 const ta = atob(req.body.ta);
 const ak = atob(req.body.ak);
 const cs = atob(req.body.cs);
 
 //get and stitch together private Key to sign JWT
 var privateKey = atob(req.body.pk);
 privateKey = ["-----BEGIN PRIVATE KEY-----", pk, "-----END PRIVATE KEY-----"].join("\n");
 
 const jwt_data = {
  "exp": Math.round(87000 + Date.now()/1000),
  "iss": oi,
  "sub": ta,
  "https://ims-na1.adobelogin.com/s/ent_gdpr_sdk": true,
  "aud": "https://ims-na1.adobelogin.com/c/" + ak
 }
 
 
 const adobe_jwt_token = jwt.sign(
     jwt_data, 
  pk,
  { algorithm: 'RS256' }
    );

 var bearer_token;
 var token_data = {
  'client_id': ak,
  'client_secret': cs,
  'jwt_token': adobe_jwt_token,
 };

 axios.post('https://ims-na1.adobelogin.com/ims/exchange/jwt/', token_data )
   .then(function (response) {
     console.log(response);
     bearer_token = response
 });
      
 res.status(200).send({
  "exchange_data": token_data,
  "token": bearer_token
 }); 
});

// Specify port
const port = process.env.PORT || 5000;

// Start the app
app.listen(port, () => {
  console.log('App started on port: ' + port);
});

‍ 您可以使用下面的 代码来完成:

app.post('/api', async function(req, res){
    //get client data from Launch Request
    const oi = atob(req.body.oi);
    const ta = atob(req.body.ta);
    const ak = atob(req.body.ak);
    const cs = atob(req.body.cs);
    //get and stitch together private Key to sign JWT
    var privateKey = atob(req.body.pk);
    privateKey = ["-----BEGIN PRIVATE KEY-----", pk, "-----END PRIVATE KEY-----"].join("\n");

    const jwt_data = {
        "exp": Math.round(87000 + Date.now()/1000),
        "iss": oi,
        "sub": ta,
        "https://ims-na1.adobelogin.com/s/ent_gdpr_sdk": true,
        "aud": "https://ims-na1.adobelogin.com/c/" + ak
    }
    const adobe_jwt_token = jwt.sign( jwt_data, pk,{ algorithm: 'RS256' });
    var token_data = {
        'client_id': ak,
        'client_secret': cs,
        'jwt_token': adobe_jwt_token,
  };

  // you can do it like this code below
  try {
    const token = await axios.post('https://ims-na1.adobelogin.com/ims/exchange/jwt/', token_data );
    console.log(token);
    res.status(200).send({ exchange_data: token_data, token })
  } catch(error) {
    console.log(error);
    res.status(500).send(error.message);
  } 
});

希望对您有所帮助。

你可以安装 npm i @eneto/axios-es6-class 然后让我们添加 api.js class:

import { Api } from "@eneto/axios-es6-class";
export class ProductsApi extends Api {
  constructor (config) {
     super(config);
     this.addProduct = this.addProduct.bind(this);
     this.getProduct = this.getProduct.bind(this);

  }

  addProduct(product) {
     return this.post("/products", {product}).then(res => res.status);
  }

  getProduct(id) {
    return this.get(`/products/${id}`).then(res => res.data);
  }
}

在您的实施方面

function endPoint (req, res, next) {
   const apiConfig = {
    withCredentials: true,
    timeout: API_TIMEOUT,
    baseURL: API_BASE_URL,
    headers: {
        common: {
            "Cache-Control": "no-cache, no-store, must-revalidate",
            Pragma: "no-cache",
            "Content-Type": "application/json",
            Accept: "application/json",
        },
    },
    paramsSerializer: (params: string) => qs.stringify(params, { indices: false }),
};

const api = new ProductApi(apiConfig);

return api.getProduct(12).then(result => res.status(200).send(result));
}