Using AngularJS to send a post request with cherrypy

I am facing an issue with posting events into a CherryPy small application that responds to GET/POST requests. When attempting to do so using AngularJS, nothing gets posted.

I'm unsure if the problem lies with AngularJS or CherryPy (CP). Cross-domain functionality is enabled in CP, but it seems unable to recognize the POST method. Strangely, the same operation works fine with CURL.

The POST method in CP is defined as follows:

    def POST(self, date, description):
    # Reading items to capture any server-side updates
    events = {
        "date": int(date.encode('ascii','ignore')),
        "description": description.encode('ascii','ignore'),
        "status":"Active"
    }
    # Storing changes
    save_events(events)
    return ('Event created\n')

Headers are set up with the following function:

def enableCrossDomain():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
cherrypy.response.headers["Access-Control-Allow-Methods"] = "GET, POST"
cherrypy.response.headers["Access-Control-Allow-Headers"] = "Cache-Control, X-Proxy-Authorization, X-Requested-With"

def OPTIONS(self):
    enableCrossDomain()
    return

A CURL call looks like this:

curl -d $EPOCH_DATE -d $EVENT -X POST 'myurl.com:1234/api/events/'

When trying the same with AngularJS:

var message = "'" + $scope.event_description + "' '" + $scope.datetime_start + "'";
            console.log(message);
            $scope.post_url = "myurl.com:1234/api/events";
            $http.post($scope.post_url,message).success();

I've attempted sending "message" as JSON and specifying it in the headers, but have been unsuccessful. Any suggestions on what I might be missing or what else I could try?

Answer №1

It appears that the solution was rather straightforward:

The issue stemmed from improper URL encoding, causing chaos in the browser; made this adjustment:

$scope.post_url = "myurl.com:1234/api/events";

To

$scope.post_url = "http://myurl.com:1234/api/events";

Then it became evident that the message was not being parsed correctly, which was highlighted by the error message:

HTTPError: (404, 'Missing parameters: message')

To simplify things, I changed the parameters to just one message and handled the splitting internally in Python, resulting in a revised POST call like this:

$scope.post_url = "http://myurl.com:1234/api/events";
var message = 'message=' + $scope.datetime_start + ',' + $scope.event_description;
$http({
    method: 'POST',
    url: $scope.post_url,
    data: message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

Additionally, it was crucial to ensure that the headers were appended to the POST message on the Python end, leading to this modification:

def POST(self, date, description):
# read items to catch any server side update
events = {
    "date": int(date.encode('ascii','ignore')),
    "description": description.encode('ascii','ignore'),
    "status":"Active"
}
# storing changes
save_events(events)
return ('Event created\n')

Which was updated to:

def POST(self, message):
    # read items to catch any server side update
    events = {
        "date": int(message.split(',')[0].encode('ascii','ignore')),
        "description": message.split(',')[1].encode('ascii','ignore'),
        "status":"Active"
    }
    # storing changes
    save_events(events)
    enableCrossDomain() # HEADERS HERE OR AJAX GETS ANGRY
    return ('Event created\n')

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

Guide on incorporating file uploads in an Angular 6 project

I am currently working on creating a component where I have implemented a file upload function in a child component and am attempting to use that component's selector in another one. Here is my project structure: - upload : upload.component.html up ...

eliminate a mesh from the view following a mouse hover event triggered by a raycaster

            When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using INTERSECTED.material.color.setHex(radioHoverColor); and reset it ...

Images are not loading in NextJs image component on a Digital Ocean deployed application

I recently encountered an issue with my NextJs project. While using the NextJs Image Component for images, everything worked perfectly fine when running locally. However, after deploying the project on Digital Ocean, all the images served through the Next- ...

Sharing state between components in NextJS involves using techniques like Context API, passing

I am trying to pass state between pages in Next.js. In my App.js, I have wrapped it in a context provider like this: import { useRouter } from 'next/router' import { ClickProvider } from '../context/clickContext' function MyApp({ Compo ...

reactjs implementation of a virtualized list

Recently, I stumbled upon the React-window library and found it to be incredibly useful. Intrigued by how it was built, I decided to try my hand at creating my own virtualized list. However, I encountered an issue where the list could only scroll up to it ...

Locate a row in an unselected data table using Jquery based on the value in a td

Is there an efficient way with jQuery to locate a td in a "legacy" datatable that contains my search value, and then navigate up the row tr? I am currently using $('#modalTable tbody').dataTable()[0].rows to retrieve all rows and then iterate th ...

Issue: React-Firebase-Hooks failing to retrieve dataHaving trouble with React-F

I've been utilizing the React-Firebase-Hooks package in my project, but I'm encountering some difficulties with its usage. In the code snippet below, the user.data().username is displayed correctly. However, when I try to use it within useState, ...

My objective is to modify a JSON object based on the chosen value from a dropdown menu

Here is the code snippet I have created using HTML: <select style="width:100px;" data-nodrag ng-model="conditions" ng-change="changingCondition(this)"> <option value="and">and</option> <option value="or">or</option> & ...

What's the best way to target an input that's appearing as it slides in from the edge of the screen?

My webpage has an element called #cols that is three times wider than the <body>. This element contains three columns, each exactly as wide as the <body>. When a button is clicked, the #cols element slides over by the width of one column while ...

Develop a carousel component using Vue.js

I'm currently working on a dashboard that needs to display cards, but I'm running into an issue. I want only four cards visible at a time, and when you click the arrow, it should move just one step to the next card. For example, if cards 1-4 are ...

Optimizing your online presence through SEO with the added benefit

My website is created using Angular and I have incorporated angular-gettext to support multiple languages: Rather than changing my site structure with domain-specific subdomains or URLs like https://en.example.com/ or https://www.example.com/en/, I curren ...

AngularJS - one-time execution of view generation from .NET controller

Currently, I have an MVC .NET application integrated with AngularJS. In my route provider configuration, I am utilizing the controllers of MVC to retrieve the views as shown below: .when('/Units', { templateUrl: 'Unit/Units' ...

Chatting in the hot spring with choices

I am looking to create a customizable dialog box in AngularJS where I can pass options such as title and message based on the caller. Essentially, I want to improve upon the standard alert() function. While the documentation has information on passing par ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

Having trouble resolving all parameters for 'Router' in Angular 2 testing with Router

Currently, I am in the process of testing a component that has Router injected in the constructor (TypeScript): constructor( private _router: Router, private dispatcher: Observer<Action>, fb: FormBuilder ) { ... } Here are the test cases ...

What is causing the PUT request to not go through when using POSTMAN?

As I navigate through the paths of my application, I encountered an issue with PUT requests that were not being fully processed by POSTMAN. Below is the configuration of my ExpressJS server: const express = require('express'); const morgan = re ...

Adding a C# variable to a URL in a Razor view using jQuery

My Razor page looks like this: @{ ViewData["Title"] = "mypage"; string ApiAddress = "https://localhost:8114/api/"; } <div> ... </div> @section Scripts{ <script> functio ...

What is the best way to switch the CSS style of a button that has been mapped

I'm currently working on toggling the CSS class for an individual button that is created from a mapped array. Although my code is functional, it toggles the CSS class for all buttons in the mapped array instead of just the one selected. ...

Issue with getStaticProps not updating fetched values in Next.js production environment

I am currently working on building a blog using Next.js. Since the back-end is taken care of by another team, I am utilizing fetch API calls in getStaticProps to retrieve my articles, even though it may be considered best practice to interact with the data ...

The term 'undefined' does not refer to an object

My div contains the following code: <em id="ProductPrice" class="ProductPrice VariationProductPrice">$75.00</em> I want to change the text color if the value changes. This is what I tried: <script> $(document).ajaxSuccess(function(){ ...