Restangular failing to apply headers during post requests

I have been encountering an issue while trying to set the header for a single post request using Restangular. Despite following the documentation here and seeking help from a similar question, the request is being sent as plain text instead of JSON.

My server-side setup includes Express 4.x and communication with MongoDB via Mongoose ORM.

Server side: server.js using Express.js 4.0

'use strict';

var express = require('express'),
    morgan  = require('morgan'),
    port =process.env.PORT || 3000,
    bodyParser  = require('body-parser'),
    methodOverride = require('method-override'),
    app = express();


app.use(morgan('dev'));             
app.use(bodyParser());              
app.use(methodOverride());          
app.use(express.static(__dirname+"/app"));

require('./config/models');
require('./config/user_ctrl');
require('./config/comt_ctrl');
require('./config/routes')(app);

app.listen(port);   
console.log('Magic happens on port: '+port); 

//Server side: routes.js
var pips = require('./user_ctrl');

module.exports = function(app){

    app.get('/api/pipplez',pips.getPipplez); //Gets all users in collection
    app.post('/api/pipplez/wan',pips.getPipplezById); //Gets the specified user

    app.all('/api/*', function(req, res) {
        res.send(404);
    });

    app.get('/*', function(req, res){
       res.send('index.html'); 
    });
};

On the client side, my configuration looks like this:

Client side: app.js after config

.factory('userServ',function(Restangular){

  var ol = Restangular.withConfig(function(conf){
    conf.setBaseUrl('/api/')
  });

  var an = Restangular.withConfig(function(conf){
    conf.setBaseUrl('/api/users/')
  });
    return{
          oldem: ol.one('users').getList(),
          wandem: an.one('one')
    }
});

Client side: userCtr.js

'use strict';

ting.controller('userCtrl', function($scope, userServ){

    $scope.pip = {
       name: ''
    };

    $scope.getOlPips = function(){

    userServ.oldem.then(function(rez){

        if(rez!=='null'){
            $scope.dem = rez;
            console.log($scope.dem);
        }
    }, function(err){
        console.log('Error!!!\n', err );
    })  
};

$scope.getWanPip = function(pip){
    //console.log(pip);
    RestServ.wandem.post(pip, {}, {'Content-Type':'application/json'}).then(function(res){
        console.log(res)      
    }, function(err){
        console.log('Error!!!\n', err);
    })
};

$scope.getOlUzas();    
});

part of the html

<form>
    <input ng-model='pip.unm' maxlength= '20' placeholder='Search for user...'>
    <button class="btn btn-primary" ng-click = 'getWanPip(pip)'>Find</button>
</form>

I have thoroughly tested the backend using Postman and confirmed its functionality. While the application can retrieve all records from the database, the POST request results in a 404 error due to the request format being sent as plain text instead of JSON. How can I resolve this issue?

Answer №1

Here are the steps you can take:

const headers = { headers: { 'Content-Type':'application/json' } };

RestServ.wandem.withHttpConfig(headers).post(pip)

Answer №2

Through my research on the internet, I discovered that Restangular typically sends form data to the server in JSON format by default. Initially, I was misled by the developer tools in Chrome. For those looking to analyze HTTP requests, I highly recommend using Fiddler. If you need to customize the header in Restangular when sending a request from a form, you can implement the following:

//Based on the example provided....
//In case Restangular does not automatically send form data in JSON format

    $scope.getWanPip = function(pip){

        RestServ.wandem.post(pip, {}, {}, {'Content-Type':'application/json'}).then(function(res){
            console.log(res)      
        }, function(err){
            console.log('Error!!!\n', err);
        })

Note the use of two empty curly braces instead of one... I am still unable to successfully execute the post request due to the data being sent within the URL instead of separately. This raises another question...

Answer №3

Avoid sending two null objects, consider sending the following instead:

.post(pip, undefined, undefined, {'Content-Type':'application/json'})

You could also use .customPOST() instead of .post().

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

Using an AngularJS directive that has a dynamic ID may cause issues with d3's ability to append

I encountered a situation where my angularJS directive works fine when I specify a hardcoded ID for appending elements, but fails to append when the ID is dynamically generated. Surprisingly, there are no errors reported by d3 or the browser. However, upon ...

What is the process for sending a JSON request?

Review the structure provided { "layer_id":"1Wn", "name":"Example Place", "latitude":"45.5037078163837", "longitude":"-122.622699737549", "span_longitude":"0.62", "extra":{ "description":"Portland", "url":"http://en.wikipedia.o ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

Use jQuery to trigger a click event when an element is in focus, unless it was clicked to

I am currently developing a website using the MDL framework. One issue I encountered is that there is no default select form element provided. After some research, I found a solution by utilizing a menu component that displays when the input is clicked. Th ...

Having trouble displaying form in a different view, form is not appearing as expected

I am facing an issue with rendering a form inside a modal. The form is being rendered but the form_for does not show up, only the inputs are visible. This prevents me from targeting the submit button, which I need for ajax functionality. My file path: Adg ...

Is it possible to use a JavaScript string as a selector in jQuery?

So, my issue is with the following JavaScript code snippet: for ( i=0; i < parseInt(ids); i++){ var vst = '#'+String(img_arr[i]); var dst = '#'+String(div_arr[i]); } I'm wondering how I can proceed in jQuery to handle ...

Vue's span function is yielding the promise object

In my Vue component, I am using the function getOrderCount to fetch the number of orders from a specific URL and display it in one of the table columns. <div v-html="getOrderCount(user.orders_url)"></div> async getOrderCount(link) { ...

Tips for extracting variables from a querystring in Express?

I am trying to retrieve values sent to the server: "/stuff?a=a&b=b&c=c" Can you please advise me on how to extract these values using express? So far, I have attempted... app.get( "/stuff?:a&:b&:c", function( req, res ){}); ...but unfo ...

Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display. HTML structure: <div id="canvas"></div> To populate the canvas with div elements, I'v ...

Tips for implementing lazy loading with an owl carousel featuring background images

Is there a way to add lazy loading to a semi custom owl carousel that uses background images instead of regular img tags? I've tried using Owl carousel's function for lazy loading but it doesn't seem to work. How can I achieve this? This is ...

Traversing an array of numerical values to find a particular ID in an SQL database

My current challenge involves splitting an array of integers and then assigning each item to a specific id DECLARE @position INT DECLARE @arrayList varchar(8000) DECLARE @len INT DECLARE @value varchar(8000) SET @arrayList = '1,2,3,4,5' IF @arr ...

The metadata template in Ext JS 4.2 is not being properly identified

First time, long time... I am currently working with Ext JS 4.2.2.1144 My issue revolves around a grid where the information fetched from the server (php) is in JSON format. This data is generated when a user realigns and resizes the columns on the grid an ...

Files with extensions containing wildcards will trigger a 404 error when accessed from the public folder in NextJS

I have successfully set up my public folder to serve static files, however I am encountering an issue with files that have a leading dot in their filename (.**). Specifically, I need to host the "well-known" text file for apple-pay domain verification, wh ...

Inserting a multidimensional array into a JSON structure

Currently, I am working on populating my mongodb database with data that needs to be in a specific format. var location1 = [2,3]; var location2 = []; location2.push(location1); location2.push(location1); var location3 = []; location3.push(location2); cons ...

Utilize the jQuery function as a callback argument

There is a jQuery plugin that I am currently working on: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head><title></title> <script type="text/javascript" sr ...

Tips for ensuring a document stays at the top of my collection when performing an update

Whenever I make changes to a document, it always ends up at the bottom of my collection. Is there a way to prevent this from happening? try { await Card.update({_id: fixedUrl}, {$push:{'comments': data}}) } catch (err) { console.log(err ...

Encountering a jQuery error while attempting to initiate an AJAX request

I'm currently working on a project in SharePoint and I want to integrate JQuery to make an ajax call from the homepage. However, when I attempt to make the call, I encounter an error stating "Array.prototype.slice: 'this' is not a JavaScript ...

Performing an AJAX GET request to the API after a set time interval

The API is constantly updating with live values, so I am attempting to fetch the data every second and display it on the webpage. Although I used a GET request call every N seconds using set_interval(), the values only load once and do not update with eac ...

Developing structured data patterns in AngularJS

I have a collection of items stored in my $scope. Each item is structured like this: function myController($scope) { $scope.items = [ { id:1, name:"apple", image:"/img/apple.png" }, { id:2, name:"banana", image:"/img/banana.png" }, { id:3, n ...