1. 程式人生 > >express轉發請求

express轉發請求

http console onf class java ring cep next -type

express

var express = require(‘express‘);
var axios = require(‘axios‘);
var qs = require(‘qs‘);
var router = express.Router();

const ajax = axios.create({
  baseURL: ‘http://test.com‘,
  headers: {
    ‘Content-Type‘: ‘application/x-www-form-urlencoded;charset=UTF-8‘,
  },
});

ajax.interceptors.request.use((config) => {
  if (config.method === ‘post‘) {
    config.data = qs.stringify(config.data);
  }
  return config;
});

router.all(‘/‘, function(req, res, next) {
  res.header(‘Access-Control-Allow-Origin‘, ‘*‘);  
  res.header(‘Access-Control-Allow-Headers‘, ‘Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild‘);  
  res.header(‘Access-Control-Allow-Methods‘, ‘PUT, POST, GET, DELETE, OPTIONS‘);  
  res.header(‘Cache-Control‘, ‘no-cache, no-store, must-revalidate‘);  
  res.header(‘Pragma‘, ‘no-cache‘);  
  res.header(‘Expires‘, ‘0‘);  

  ajax({
    method: req.method.toLowerCase(),
    url: req.originalUrl,
    data: req.body,
  }).then(response => {
    res.send(response.data);
    console.log(response.data);
    console.log(req.body);
  }).catch(err => {
    console.log(err);
  });

  if (req.method == ‘OPTIONS‘) { res.send(200); }
});

module.exports = router;

  

express轉發請求