Axios未传递Content-Type头信息

3
我在后台运行一个Odoo实例,并创建了一个自定义模块,其公开了一个Web控制器,如下所示:

Web控制器

# -*- coding: utf-8 -*-
from odoo import http
import odoo
from odoo.http import Response, request
from werkzeug import wrappers
import json


class VueWebServices(http.Controller):
    @http.route('/vuews/msg/', auth='none', type='json', methods=['POST', 'GET', 'OPTIONS'], csrf=False)
    def answermsg(self, **post):
        product_ids = request.env['product.product'].sudo().search([])
        dict = {}
        r = request
        d = request.httprequest.data
        dv = http.request.params
        for k in product_ids:
            tuple = {}
            tuple.update({"name":k['name']})
            tuple.update({"id": k['id']})
            dict.update(tuple)
        return json.dumps(dict)

为了允许 CORS,我还通过 Nginx 代理 Odoo。以下是 nginx.conf 的样子:

nginx.conf

upstream odoo {
        server 127.0.0.1:8069;
    }
    server {
        listen  443 default;
        server_name localhost;
        root    c:/nginx/html;
        index   index.html index.htm;

        access_log c:/nginx/logs/odoo.access.log;
        error_log c:/nginx/logs/odoo.error.log;

        proxy_buffers 16 64k;
        proxy_buffer_size 128k;

        location / {
            proxy_pass  http://odoo;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            proxy_redirect off;

            proxy_set_header    Host            $host:$server_port;
            proxy_set_header    X-Real-IP       $remote_addr;
            proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto https;

            add_header    'Access-Control-Allow-Origin' '*' always;
            add_header    'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
            add_header    'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept' always;
            add_header    'Access-Control-Request-Headers' 'Content-Type' always;
            add_header    'Access-Control-Allow-Credentials' 'true' always;
        }

        location ~* /web/static/ {
            proxy_cache_valid 200 60m;
            proxy_buffering on;
            expires 864000;
            proxy_pass http://odoo;
        }


    }

当我尝试通过Postman访问路由时,它按预期工作。但是当我尝试通过axios访问它时,我得到了400 BAD REQUEST的错误。在odoo控制台中,它抛出了这个错误:Function declared as capable of handling request of type 'json' but called with a request of type 'http' 这是我的Vue JS应用程序如何查询控制器的方式:
axios({
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Cache-Control": "no-cache",
      },
      data: {
        "message": "Hello World"
      },
      url: "http://localhost:443/vuews/msg"
    });

我明显传递了“content-type: 'application/json'”头部信息,那么出了什么问题?

可能是重复问题如何在Odoo控制器中获取JSON数据? - tony19
@tony19 不是重复的问题。我已经尝试过将控制器装饰器从type ='json'修改为type ='http',然后发送请求。这对GET请求很有效,但是当我想以json格式向服务器发送数据时,为了将其从请求正文中取出,它需要是json类型,因此需要type ='json'。这就是Axios失败的地方。我猜这是CORS问题,但我不知道如何解决它。 - Kyle Sentient
1个回答

1

最终解决了这个问题。它是一个CORS问题,我通过修改nginx.conf中的代码来解决:

upstream odoo {
        server 127.0.0.1:8069;
    }
server {
        listen  443 default;
        server_name localhost;
        root    c:/nginx/html;
        index   index.html index.htm;

        access_log c:/nginx/logs/odoo.access.log;
        error_log c:/nginx/logs/odoo.error.log;

        proxy_buffers 16 64k;
        proxy_buffer_size 128k;

        location / {
            proxy_pass  http://odoo;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            proxy_redirect off;

            proxy_set_header    Host            $host:$server_port;
            proxy_set_header    X-Real-IP       $remote_addr;
            proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header    X-Forwarded-Proto https;


            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' 'http://localhost:8080'; 
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; 

                add_header 'Access-Control-Allow-Headers' 'DNT,access-control-allow-origin,x-openerp-session-id,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'application/json charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
            }
            if ($request_method = 'POST') {
                add_header 'Access-Control-Allow-Origin' 'http://localhost:8080'; 
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,access-control-allow-origin,x-odoo-session-id,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; 
                add_header 'Access-Control-Allow-Credentials' 'true';
            } 

            if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' 'http://localhost:8080';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,access-control-allow-origin,x-odoo-session-id,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
                add_header 'Access-Control-Allow-Credentials' 'true';            
            }

        }

        location ~* /web/static/ {
            proxy_cache_valid 200 60m;
            proxy_buffering on;
            expires 864000;
            proxy_pass http://odoo;
        }


    }

请注意:在Access-Control-Allow-Origin标头中,我指定了我正在工作的应用程序的地址和端口http://localhost:8080。您可以将“*”替换为任何适合您的地址。此外,Access-Control-Allow-Credentials标头不是必需的,除非您计划从应用程序发送身份验证cookie /标头以访问服务器上的某些路由。在我的情况下,我向我的axios调用添加了参数withCredentials:true,因此我不得不将Access-Control-Allow-Credentials:true标头添加到nginx.conf中,并且还必须指定我的vue应用程序的地址和端口(localhost:8080)。
另外,如果您正在使用Odoo Web控制器,则可以通过简单地将cors ='*'装饰器添加到您的Web控制器声明中来避免使用Nginx。以下是一个示例:
@http.route('/vuews/msg/', auth='none', type='json', methods=['POST', 'GET', 'OPTIONS'], cors='*', csrf=False)

奖励: 如果您计划通过HTTP POST请求将数据发送到Odoo Web控制器,请确保将其包含在params: {}中,如下所示:

data: {
        jsonrpc: '2.0',
        method: 'call',
        id: 1,
        params: {
          message: 'Hello World'
        }
      },

如果您在控制器函数参数中声明了post对象,您就可以通过后端访问它:

@http.route('/vuews/msg/', auth='none', type='json', methods=['POST', 'GET', 'OPTIONS'], csrf=False)
    def answermsg(self, **post):
    // do something here... ex: data = post;

我希望这能帮助那些遇到类似问题的人。如果需要帮助,请随时联系我。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接