Send data in JSON format from an AngularJS client to an Express server

Having an issue when trying to send a JSON Object from an AngularJS $http service to an Express Server. The server receives an empty object: "{}"

I've looked at this topic, but it hasn't resolved my problem: angular post json to express

This is the code for the Angular client:

self.postTicket = function(ticket){
        $http({
            url: baseUrl+"features/",
            method: "POST",
            body: ticket,
            headers: {'Content-Type': 'application/json'}})
}

I have verified that the "ticket" object is not empty

And here is the code for the Express server:

var express = require("express");
var request = require("request");
var bodyParser = require('body-parser')


var app = express();

app.use(bodyParser.json({}));

app.post('*', function (req, res) {
    console.log(req.body);
    res.status(200).send('OK');
});


app.listen(9000);

Any help in resolving this issue would be greatly appreciated. Thank you.

Answer №1

Replace body with the data property when making a request using $http

$http({
            url: baseUrl+"features/",
            method: "POST",
            data: ticket,
            headers: {'Content-Type': 'application/json'}})

Answer №2

Swap

self.sendTicket = function(ticket){
    $http({
        url: baseUrl+"features/",
        method: "POST",
        body: ticket,
        headers: {'Content-Type': 'application/json'}})

for

self.postTicket = function(ticket){
    $http({
        url: baseUrl+"features/",
        method: "POST",
        data: ticket,
        headers: {'Content-Type': 'application/json'}})

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

Generating an interactive table using JSON with Angular 5

Can a dynamic table with dynamic columns be created based on a JSON object using Angular 5? If yes, how? The API response includes the following JSON: { "ResponseStatus": true, "ResponseData": [ { "Parent": "Company 1", ...

Transforming a JSONArray into a regular Array

I transformed a regular array of user-defined objects into a JSON Array. Now I'm wondering how to convert the JSONArray back to a normal array of the same type. In order to accomplish this, I am utilizing Json for shared preference in an Android appli ...

Error message indicating that the function is not defined within a custom class method

I successfully transformed an array of type A into an object with instances of the Person class. However, I'm facing an issue where I can't invoke methods of the Person class using the transformed array. Despite all console.log checks showing tha ...

ways to disrupt a timeout

I am attempting to incorporate a functionality similar to this example: https://www.w3schools.com/jsref/met_win_cleartimeout.asp On my personal website: If you enter certain characters in the input field, select one of them, and then pause for 5 seconds, ...

Testing React Hooks in TypeScript with Jest and @testing-library/react-hooks

I have a unique custom hook designed to manage the toggling of a product id using a boolean value and toggle function as returns. As I attempt to write a unit test for it following a non-typescripted example, I encountered type-mismatch errors that I' ...

Using AJAX to submit a form with a file to Symfony results in $form->isValid returning false

Utilizing Angular JS code, I employ a method to submit a file and additional fields (along with a CSRF token) to a Symfony controller. var formObject = new FormData; formObject.append('email', self.careers[index].application.email); formO ...

Updating a URL once AngularJS has finished processing it

Currently, I am utilizing Primo, an AngularJS app developed by Ex Libris. This application functions as a library catalog, enabling users to explore both physical and digital collections within the library. Despite not having direct access to the original ...

Display the contents of a <div> tag from one HTML file onto another HTML file

Recently I embarked on learning HTML and came across a peculiar doubt. My goal is to create a section div on the first page that changes dynamically based on the menu item clicked, rather than redirecting to another HTML page. I've experimented with s ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Transition from FadeOut to loading content and displaying it

Is there a way to simply display the content after loading without using fadeIn? $(function() { $('.hovers').click(function(event) { var target = $(this).attr('href'); window.location.hash = target; $.ajax({ url: ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

The user ID encountered a CastError: Unable to convert the value "64e310ad9d821c557b4f9bc7" (of type string) to an ObjectId for the "userId" path due to a BSONError

When passing the "id" to the hidden input value in EJS, a bson error is encountered. The data is correctly stored in the database, but the error appears in the EJS file. The error occurs in the form.ejs file: form.ejs <!DOCTYPE html> <html lan ...

Steps for updating a text section beneath a carousel

I'm looking to enhance my webpage with a bootstrap carousel, which is pretty standard. However, I want the content under each slide to change dynamically, but I'm struggling to make it work. As a newbie, I could use some guidance. I've atte ...

Ways to insert text at the start and end of JSON data in order to convert it into JSONP format

Currently, I am working on a project where I need to add a prefix "bio(" and a suffix ")" to my JSON data in order to make it callable as JSONP manually. I have around 200 files that require this modification, which is why I am looking for a programmatic ...

JavaScript data manipulation: Determining percentage change within a nested JSON structure

Provided is a JSON file structured like this... data =[ { key: "london", values: [ {day: "2020-01-01", city: "london", value: 10}, {day: "2020-01-02", city: "london", value: 20}, {day: " ...

Embracing the Unknown: Exploring Wildcard Values

I have a code snippet below that has a wildcard * in it. I'm looking for suggestions on how to make the * accept any number. Any thoughts on this? $('body').on('click', '.custom_295_*-row', function(){ var href = "htt ...

Generating perspectives from a HashMap contained within an ArrayList

I've been struggling with this logic problem, but I believe I'm getting closer. I am extracting values from a JSON response and storing them in a HashMap before adding the HashMap to an ArrayList. doInBackground protected String doInBackground( ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...

The process of implementing server-side rendering for React Next applications with Material-ui using CSS

I have developed a basic React application using Next.js with an integrated express server: app.prepare() .then(() => { const server = express() server.get('/job/:id', (req, res) => { const actualPage = '/job' const ...

WebRTC error encountered: Unable to add ICE candidate to 'RTCPeerConnection'

Encountering a specific error in the browser console while working on a project involving p2p video chat. The error message is Error: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': The ICE candidate could not be added.. Int ...