Exploring the management of session state in AngularJS with JSON API authentication

I am trying to create a new post through the wp-rest API using a mobile app. To do this, I need to log in with a form. The authentication with json api auth is successful when I submit my username and password. However, when I attempt to create a new post with the wp-rest API, I encounter an error saying "You don't have permission to do this." Even though I am logged in!

Here is my code:


       var data={"title":"Hello World!","content_raw":"Content","excerpt_raw":"Excerpt"};

    $scope.register = function() {

        $http({
            method: 'POST',
            url: 'http://url.com/provawp/wp-json/wp/v2/posts',
            data: data,
            headers: {'Content-Type': 'application/json'}
        })
        .success(function(data, status, headers, config) { 
            alert("City added successfully!"); 
        }) 
        .error(function(data, status, headers, config) {
        }).
        catch(function (error) {
         alert("Error!");
        console.log("error : " + JSON.stringify(error) );

       }); 
}

Answer №1

When incorporating web tokens, consider placing your token directly into the http header through the use of http interceptors

Answer №2

Here is an example of how you can use this code snippet:

$http({
        method: 'POST',
        url: 'http://url.com/provawp/wp-json/wp/v2/posts',
        data: data,
        headers: {
                 'Content-Type': 'application/json',
                'Authorization' : 'bearer Token123#456'
               }
    })

If you encounter any issues, make sure to reach out to your back end developer.

bearer is a prefix used in the Authorization header.

Your specific Token123#456 serves as your Authorization token.

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

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...

Modifying the color of a header through clicking on a specific anchor link

My goal is to create a fixed side nav bar on my webpage with an unordered list that links down the page using anchors. In addition, I want to dynamically change the color of an h2 element based on which item in the fixed nav bar is clicked on. For instan ...

PHP does not display the user_temp variable

I created a straightforward application to display the current weather. //------------------------------------------------connect to API and fetch data $appid = ""; $api_url = "http://api.openweathermap.org/data/2.5/weather?q=" . $user_city . ...

Utilizing Ajax in conjunction with Ruby on Rails

I have a question that may be quite basic (I am new to Rails 3). I am looking to implement Ajax functionality where once a user clicks on a link, it triggers a $.post call and initiates some server-side changes. Within the _share partial file, I currently ...

Preserve the variable alterations for future promises

I have implemented promises in my database access using elasticsearchjs, which utilizes Bluebird. Each ID in the list triggers a new query, and I need to identify the failing query by its ID. const idList = ['id1', 'id2', 'id3&apo ...

Issue in ReactJS: Function with parameters is returning undefined values

Having a React app, I am currently facing an issue while trying to convert temperatures from Kelvin to Fahrenheit. Although I have set up a simple function to achieve this, I am consistently receiving undefined values. // Within the CityWeatherComponent i ...

Utilizing the request body value within the .withMessage() function of the Express validator chain

I am looking to showcase my express validator errors with the specific value entered by the user. For instance, if a user types in an invalid username like "$@#" (using a regex that I will provide), I want to return my error message as follows : { "er ...

Obtain the in-flow position of a DOM element

alert("Incorrect (red): " + document.getElementById("target").getBoundingClientRect().top); alert("Proper (blue): " + document.getElementById("wrapper").getBoundingClientRect().top); #target { transform: translate(20px, -20px) rotateZ(20deg); backgroun ...

Tips on resolving issues with cellclickable functionality in Angular with gridster2

VERSION: ^9.3.3 HTML <button (click)="toggleEditing()">{ editing ? 'cancel' : 'editing' }</button> <button>ADD</button> <gridster [options]="options"> &l ...

Reacting to a click event to display a new image

I'm looking to create a webpage with multiple images where clicking on one image will open another image with its description. The images are stored locally in my library. I tried using the href attribute in the html tag, but it doesn't accept lo ...

Removing a child element in ReactJS that was dynamically created based on a count

Currently, I'm working on a project with two React components: TrackSection (the parent element) and TrackItem (the child). The TrackSection contains a button that adds a new TrackItem every time it is clicked by incrementing the numTracks variable. W ...

What is the reason for the initial DOM operation taking significantly longer than subsequent ones?

Why is the first operation much more despite the subsequent manipulation of the DOM being practically identical in time when both are written with the realization in JS and jQuery? Link to Javascript source // ES5 // Sending a message function sendMessa ...

I have an npm package that relies on X (let's say material-ui). What is the best way to prevent users from having to install

Hey everyone, I recently released an npm package called X that relies on material-ui as a dependency. While many users of X already have material-ui installed, there are some who do not. How can I ensure that those who have material-ui installed continue t ...

"There seems to be an issue with the KeyListener function in

The error I'm encountering is: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null I'm unsure about what went wrong. The intention behind the code was to store the result of the selected radio button into a ...

"Integrating a typeface.json font file into your three.js project: A step-by

I'm looking to incorporate 3D text into my website using the following code (reference: Labelling the vertices in AxisHelper of THREE.js): var textGeo = new THREE.TextGeometry('Test', { size: 10, height: 5, ...

Sharing various data from Express to Jade is quite simple and can be done

I have a series of variables that are checking against a condition to determine if they return true or false. While I've been able to print these results using console.log, I now need to display them in a jade template. However, I'm encountering ...

Are you sure that $(window.document).ready(function () { ... } is truly prepared?

Currently, I have a function that uses window.open to open a new window with a URL from the same host/domain as the current page: function openWindow() { var fswin = window.open(url, msg); $(fswin.document).ready(function () { setWindowTitle(f ...

Is there a way to display the icon in Javascript?

I added a glyphicon element to my page but set its visibility to hidden using CSS. My goal is to reveal the glyphicon (#gl1) when users input text and click the "post" button, but I'm encountering an issue where the glyphicon doesn't show up when ...

Transition from the previous image to the new one with a fading effect to enhance list item navigation

I've been working on implementing a sprite image for each list item (home, services, and contact) in my project. Using CSS, I've managed to move the position on hover successfully. However, I now want to add a fade effect to the transition instea ...

Error Encountered in AngularJS: Request Unexpected (No Additional Requests Anticipated)

In my AngularJS project, I'm facing a challenge in writing unit tests to verify that executing a promise's then function changes the location.url. The function login within the AuthenticationService service is responsible for this behavior. Belo ...