nodejs跨域請求涉及到的一些問題

自己試了好久,終於把node.js的代理問題弄清了個大概。首先我本地項目在跨域方面會先請求一個options,成功後纔會請求post,於是我一開始在代理中用的代碼:

const express = require('express');
const app = express();
app.use('/print/*', proxy({
    target: 'http://localhost:8099',
    changeOrigin: true,
    // 修改響應頭信息,實現跨域並允許帶cookie
    onProxyRes: function (proxyRes, req, res) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Credentials', 'true');
    },
    // 修改響應信息中的cookie域名
    cookieDomainRewrite: false // 可以爲false,表示不修改
}));

問題有兩處,1.我的請求鏈接爲http://localhost:9001/print,它根本就不會進這個路由,因爲/*是多餘的。2.解決問題一後,只有options會進入,post並不會進入

響應頭裏缺少了個重要的:res.header('Access-Control-Allow-Headers', 'Content-Type');

然後我又加了個:

app.post('/print', (req, res) => {
    const target = 'http://localhost:8099/print';
    console.log(target, req.body);
    axios.post(target, req.body).then((response) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        res.header('Access-Control-Allow-Credentials', 'true');
        res.json(response.data);
    }).catch((err) => {
        console.log('poi err' + err.message);
    });
});

果然代碼不會進入這個post,畢竟前面存在一個use。於是我把use那段註釋了,但因爲options請求不通所以也不會進入post的路由裏。之後我的關注點轉移到了組件上,把組件中的請求改成了:

axios.post(url + '/print', params, {
  headers: { 'Content-Type': 'multipart/form-data' },
});

這時候居然後端接收到了post請求了,但問題在於參數怎麼傳都是空……這時試了各種application/json、JSON.stringify()、new FormData()都失效之後又把headers刪了。

之後突發奇想,把代理第一段中的use改成了opstions,然後居然正常得通過app.opstions和app.post,而且參數也被後端正常接收到了。

最後又測試了一些東西,發現即使不要app.opstions,把app.post改成app.use,也是行得通的,但那樣後端會返回兩次數據(第一次的數據因爲是options沒有參數,所以是有問題),感覺並不是很正規,還是回到原代碼好了:

app.options('/print', proxy({
    target: 'http://localhost:8099/',
    changeOrigin: true,
    onProxyRes: function (proxyReq, req, res) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
    },
    cookieDomainRewrite: false
}));
app.post('/print', (req, res) => {
    const target = 'http://localhost:8099/print';
    axios.post(target, req.body).then((response) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        res.json(response.data);
    }).catch((err) => {
        console.log('poi err' + err.message);
    });
});

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章