问题
I'm calling my express route (domain.com/api) from another domain (domain1.com). So I've set up Express to accept POST requests to the route /api and signing a JWT before exchanging the JWT via Axios for a Bearer access token.
I cannot seem to get the Axios post request to fire. Is is possible it's a firewall thing? How can I see where the error lives? Forgive me, I'm still new to Node/Express.
Here is my pertinent code:
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);
});
回答1:
👨🏫 You can do it with this code below: 👇
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);
}
});
I hope it's can help you 🙏.
回答2:
well you could install npm i @eneto/axios-es6-class
then let's add our 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);
}
}
on your implementation side
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));
}
来源:https://stackoverflow.com/questions/59881442/axios-post-isnt-running-inside-nodejs-express-route