【问题标题】:Axios POST isn't running inside NodeJS/Express RouteAxios POST 没有在 NodeJS/Express Route 中运行
【发布时间】:2020-05-09 21:29:22
【问题描述】:

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

我似乎无法触发 Axios 发布请求。有可能是防火墙吗?如何查看错误所在的位置?原谅我,我还是 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);
});

【问题讨论】:

    标签: express axios digital-ocean


    【解决方案1】:

    ?‍? 你可以用下面的代码做到这一点: ?

    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);
      } 
    });
    

    希望对你有帮助?。

    【讨论】:

      【解决方案2】:

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

      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));
      }
      

      【讨论】:

        猜你喜欢
        • 2020-03-23
        • 1970-01-01
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 2019-01-20
        • 2016-02-25
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多