鍍金池/ 問答/HTML/ 怎么在express中使用axios?

怎么在express中使用axios?

express配置中已經(jīng)使用了中間件http-proxy-middleware并且配置了轉(zhuǎn)發(fā)

app.use('/api', proxy({
    target: 'http://x.x.x.x.',
    changeOrigin: true,
    pathRewrite: {
        '^/api': '/'
    }
}));

而在 app.get 方法中使用 axios 的時候會報錯:

app.get('/index/test', function(req, res) {
    axios.get('/api/index/getdata.html?page=1') // 這里如果寫成 http://x.x.x.x/index/getdata.html?page=1 就不會報錯
        .then(result=>{
            console.log(result);
            return res.send('test');
        })
});

output

(node:12952) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: Request failed with status code 404
(node:12952) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

其中我想要使用 /api ,不知道怎么實(shí)現(xiàn)?

回答
編輯回答
帥到炸

你這里需要指定協(xié)議,域名和端口呀,不然它怎么知道你去請求哪兒;
不像瀏覽器,瀏覽器訪問一個網(wǎng)站,這些都知道了的
在這兒可以使用
http://127.0.0.1:port/api

2017年7月10日 01:56
編輯回答
朕略傻

調(diào)整代理

proxyTable: {
      '/': {
        target: 'http://localhost:8888/api',
        changeOrigin: true,
        pathRewrite: {
          '^/': '/'
        }
      },
    },

在你的vue文件中引入axios,然后使用,如下:

<script>
import axios from 'axios'
export default {
  data(){
    return{
      titleCate:[],
    }
  },
  mounted(){
    this.init();
  },
  methods:{
    init(){
      axios.get('/titlecate').then((response)=>{
        this.titleCate = response.data;
      });
    }
  }

}
</script>

以上

2018年4月22日 04:28