Axios failing to include Content-Type in header

I have set up an Odoo instance in the backend and developed a custom module that includes a web controller. Here is the code for the web controller:

Web Controller

# -*- 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)

To enable CORS, I am using Nginx as a reverse proxy for Odoo. Below is the configuration in 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;
        }
    }

While testing the route with Postman, everything works correctly. However, when attempting to call it through Axios, I receive a 400 BAD REQUEST. In the Odoo console, the following message appears:

Function declared as capable of handling request of type 'json' but called with a request of type 'http'

This is how my Vue JS application is making the request to the controller:

axios({
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Cache-Control": "no-cache",
      },
      data: {
        "message": "Hello World"
      },
      url: "http://localhost:443/vuews/msg"
    });

Despite including the header

content-type : 'application/json'
, something seems to be causing an issue. What could be the problem?

Answer №1

After much troubleshooting, I finally managed to resolve this problem. It turned out to be a CORS issue which I was able to fix by making changes to the code in 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 settings
        }

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

A note to consider: In the Access-Control-Allow-Origin header, make sure to specify the correct address and port of your application. You can also use '*' as a wildcard if needed. Adding the Access-Control-Allow-Credentials header is essential only when handling authentication cookies or headers between the application and server. Ensure to configure it accordingly based on your requirements.

If you are working with an Odoo web controller, you have the option to include the cors='*' decorator in your declaration instead of using Nginx.

Additional tip: For sending data via HTTP POST to an Odoo web controller, utilize the params: {} section for specifying the required parameters.

By following these steps and suggestions, you should be able to overcome similar challenges. Do not hesitate to reach out if further assistance is needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problems arising from the implementation of CSS modules in React applications

As a beginner in React, I recently started learning how to utilize CSS modules within my React projects. However, I encountered an error that read: Failed to compile. ./src/components/Header/Header.js Module not found: Can't resolve './Header.mo ...

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...

Setting an ID attribute with EditorFor

I have been working with a template for Views and utilizing a lot of JQuery to extract input from an EditorFor. Due to this, I prefer sticking with my current setup using EditorFor instead of something like <input type="text"> I recently added a dat ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Is your Vuex state data not persisting properly?

I am currently developing an admin panel using Vue.js and utilizing Vuex for state management. store/module/home/home.js: import instance from "../../../services/Http"; const state = { usersCount: 0, customersCount: 0, chefsCount: 0, d ...

What is the best way to make changes to the DOM when the state undergoes a

I've programmed the box container to adjust dynamically based on input changes. For instance, if I entered 1, it will generate one box. However, if I modify the input to 2, it mistakenly creates 3 boxes instead of just 2. import React from 'rea ...

Creating aliases for a getter/setter function within a JavaScript class

Is there a way to assign multiple names to the same getter/setter function within a JS class without duplicating the code? Currently, I can achieve this by defining separate functions like: class Example { static #privateVar = 0; static get name() ...

Transferring a Query between Domains with the Help of JavaScript

It is necessary to develop a function that generates a query based on the user's input of "Test" in an INPUT on Site A (SiteA.com) and then redirects to Site B within the same window, passing along the query (SiteB.com/search.aspx?k=test). Code snipp ...

Tips for running two elixir tasks consecutively?

Check out this piece of code: var gulp = require('gulp'), fs = require('fs'); gulp.task('taskOne', function() { return gulp.src('folder1/file1.js') .pipe(gulp.dest('folder2')); }); gulp.t ...

Issue with NodeJS SQL Login: Received error (ERR_HTTP_HEADERS_SENT): Headers cannot be set after being sent to the client

Hi there, I am fairly new to working with nodeJS and I have encountered an issue that I suspect lies within the second if statement inside "db.query..." in the code provided below. An error message showing ERR_HTTP_HEADERS_SENT]: Cannot set headers after ...

Angular.js filter issue: "Error: textProvider is not recognized provider"

I implemented a custom filter for my AngularJS project that is similar to the one in this fiddle http://jsfiddle.net/tUyyx/. myapp.filter('truncate',function(text,length){ var end = "..." text = text.replace(/\w\S*/g, function( ...

Creating a visual representation of a loading spinner prior to implementing debounce technology

Is there a way to set this.isLoading = true before the debounce function is executed in this method? I'm trying to show a loading spinner while making an asynchronous call with axios. methods: { searchAdminUsers: _.debounce(function(quer ...

Verify whether the element retains the mouseenter event after a specified delay

I recently implemented some blocks with a mouseenter and mouseleave event. <button onMouseEnter={this.MouseEnter}>hover</button> MouseEnter(e) { setTimeout(() => { // Checking if the mouse is still on this element // Pe ...

Angular image source load test encountered an error

<div class="col-xs-4 col-sm-4 col-md-4"> {{jsonData[current].profilepic}} <div ng-if=IsValidImageUrl(jsonData[current].profilepic)> <img id="pic" ng-src="{{jsonData[current].profilepic}}" alt=""/> </div> < ...

What is the method to invoke a function within a factory in angularjs by using a string parameter?

I have a complex logic that I want to encapsulate in an AngularJS factory for easy use with dependency injection. The challenge is that the logic is dynamic, so I don't know in advance what functions will be available. What I have is a string represen ...

Display data in a template upon receiving a response from the server

Hello, I am currently in the process of developing my very first Angular application and could use some assistance. Specifically, I am working on a component that serves as an image search box. When a user inputs a search query, a request is sent to an API ...

The jQuery pop-up fails to activate on the initial click

I have multiple "Buy Now" buttons for different products. If the button is labeled as "sold-out," it should not do anything, but if it's available, it should trigger a jQuery Magnific Popup. Currently, the popup only opens after the second click becau ...

Guide on incorporating text input areas into specific positions within a string

Looking for a way to replace specific words in a string with input fields to enter actual values? For example... Dear Mr. [Father_name], your son/daughter [name] did not attend class today. This is what I want it to look like... Dear Mr. Shankar, your ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

When attempting to load a JSON file, a Node.js loader error is triggered stating "Error: Cannot find module 'example.json'" while running transpiled code through Babel

When it comes to importing or requiring JSON (.json) files in TypeScript code, there have been multiple questions addressing similar issues. However, my query specifically pertains to requiring a JSON file within an ES6 module that is transpiled to the cur ...