vueドメイン間問題およびpostパラメータ

2647 ワード

  • 方案一:config.index.jsでwebpackを設定する最初の案はフロントでJSON形式のデータを転送することである.「Content-Type」の設定:
  • 'application/json;charset=UTF-8',  :
    axios.post('/user',JSON.stringify(params),{
    	headers: {
            'Content-Type': 'application/json;charset=UTF-8'
    	 }
    })
      .then(function (res) {
        console.log(res);
      })
      .catch(function (error) {
        console.log(error);
      });
    

    また,バックグラウンドで受信パラメータを変更する方式を@RequestBodyに変更した.
    この方法は主にブログを参照してください.https://blog.csdn.net/CarryBest/article/details/80079364
    このブログでは、単一のパラメータを受信する場合は可能ですが、複数のパラメータを受信すると、エラーが発生します.解決策は,バックグラウンドで受信したパラメータがMapタイプまたは複数のパラメータからなるクラスのこのタイプを設定することである.
  • シナリオ2 URLSearchParamsを使用したAPI:
  •  const params = new URLSearchParams();
    params.append('param1', 'value1');
    params.append('param2', 'value2');
    axios.post('/foo', params);
    

    しかし、このAPIのブラウザ互換性は理想的ではないが、polyfillがあり、互換性スキームを提供している.(https://github.com/WebReflection/url-search-params )
  • コード
  • module.exports = {
      dev: {
        // Paths
        assetsSubDirectory: 'static',
        assetsPublicPath: '/',
        proxyTable: {
          '/api': {
            target: ' http://172.17.186.222:8999/',
            changeOrigin: true,
            pathRewrite: {
                '^/api': ''
            }
        }
        },
    
     methods: {
        login(forName) {
          this.$refs[forName].validate(valid => {
            if (valid) {
              this.$axios.post('api/user/login',{
                name:this.loginForm.username,
                password:this.loginForm.password,
              },
              { headers: { 'Content-Type': 'application/json' } 
              }
              ).then(res=>{
                if(res.data.code===0){
                  Cookies.set("userName",res.data.data.username);
                  this.userName=res.data.data.username;
                  this.$router.push("/index/statistics");
                }else if(res.data.code ===50010){
                  this.$message.closeAll();
                    this.$message({
                      duration: 1600,
                      message: "        !",
                      type: "error"
                    });
                }
                else{
                  this.$message.closeAll();
                    this.$message({
                      message: res.data.msg,
                      type: "error"
                    });
                }
              })
             
            } else {
              console.log("error submit!!");
              return false;
            }
          });
        }
      }
    

    リファレンス