Unauthorized POST request made in IBM Cloud Dialog

I keep encountering an error message after clicking the button:

"POST 401 (Unauthorized)"

Check out my code below:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
    <button onclick="makePostCall()">Click me</button>
    <script>
        makePostCall = function() {
            var username = "c0ae64ef-410a-4f74-b875-ef52dee90686";
            var password = "9K2q4byngzo7";
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'https://watson-api-explorer.mybluemix.net/dialog/api/v1/dialogs/c8e08780-b08b-4cdb-8b8c-ea118863fcd1/conversation', true);
            //xhr.withCredentials = true;
            xhr.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:80');
            xhr.setRequestHeader('Access-Control-Allow-Credentials', '*');
            xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
            xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type', 'application/json', 'Authorization');
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.setRequestHeader('Authorization', 'Basic ' + btoa(username + " " + password));
            xhr.send('{"query":{"match_all":{}}}');
        }
    </script>

</body>

</html>

Answer №1

It's important to keep your dialog service credentials secure and not expose them in your code. If they have been compromised, it is advisable to delete the current credentials and generate a new set.

Due to browser domain cross-site restrictions, it is recommended that client-side JavaScript should call a proxy API on your server rather than directly interacting with external APIs. Referencing for Swagger documentation is the correct approach, as using Swagger APIs from a browser-based client can lead to security vulnerabilities.

Your application should have its own entry points acting as proxies to the real URL of the Dialog service API, which is accessed through .

If you are passing a dialog ID into your proxy, you must have obtained it either by creating it using authentication credentials or requesting a list of dialogs. Both methods require valid service credentials.

After organizing your architecture, interactions with the conversation API can be achieved using curl commands like:

curl -u "{username}":"{password}" \
   -X POST
   --form conversation_id={conversation_id}
   --form client_id={client_id}
   --form input="Hi Hello"
   "https://gateway.watsonplatform.net/dialog/api/v1/dialogs/{dialog_id}/conversation"

Detailed examples of how to interact with the service can be found in the documentation at https://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/dialog/api/v1/

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

"Troubleshooting: Issue with array_shift() function unable to identify

My latest project involved creating a Web App for a Delivery service that utilized Google Maps and queried a database for open deliveries. However, I encountered an issue when attempting to use array_shift() on the delivery array through an ajax call - the ...

Is there a way to trigger a CSS3 animation to play when scrolling down and then play in reverse when scrolling up?

Using a blogger website, I have successfully set up sticky navigation. However, when scrolling back up, the navigation bar pops back into place without any animation. I am looking for a solution to smoothly return the navigation bar to its original positio ...

When attempting to reference an object from a JSON file using a variable, the object fails to be retrieved

A script combining JavaScript with a JSON file to retrieve room information based on the room ID. function getRoomInfo(roomID) { const roomsDB = require("./rooms.json") let formattedRoomID = "r" + roomID console.log(roomsDB[formattedRoomID]) } ...

What is the method for utilizing MongoDB to locate documents that correspond with a specific custom field?

I'm currently working on a task in node.js that involves searching for all documents matching a custom field. Below is the node.js code snippet: req.app.db.models.Property.find({ user: { id: req.params.id } }).exec(function(err, user) { if ...

Tips for leveraging Angular resources with Sails

I recently started using angular resource with sails. var roles = sailsResource('roles').query(); // GET /roles $scope.rolesList = roles; angular.forEach($scope.rolesList, function(role) { console.log("Role: " + role); }); The output is sh ...

Error: Attempting to access the style property of an object that is not defined

My goal is to adjust images by clicking buttons. The JavaScript code should update the image style upon button click, but I encounter an error. Surprisingly, when I try the same operation in my console, it works perfectly. Below is the HTML code snippet: ...

Executing Javascript to populate a div element with content based on its CSS class

Is there a way to isolate my View (HTML & CSS files) within a controller like JavascriptCode/AJAX, so that upon page load, only the controller binds the data to a specific element such as a DIV based on its class? Do you think this is achievable? If so, ...

Navigating through an array for drawing a polyline on Google Maps

Is there a way to efficiently loop through an array of coordinates in order to set markers and draw a line on Google Maps using the path property? Please see the example below for clarification: const lineSymbol = { path: google.maps.SymbolPath.FORWARD_ ...

Encountering error while trying to set up Hardhat using npm - "npm ERROR! Invalid URL code"

PS C:\Users\jawad\OneDrive\Desktop\NFT Project> npm install --save-dev hardhat npm ERR! code ERR_INVALID_URL npm ERR! Invalid URL npm ERR! A complete log of this run can be found in: C:\Users\jawad\AppData\L ...

Creating a Countdown using JavaScript within HTML

I have been attempting to develop a basic HTML countdown using JavaScript, utilizing this guide as a reference. Unfortunately, the countdown is not functioning as expected. My files are hosted on 000webhost. Can you identify any mistakes in my code? < ...

leveraging npm packages in Vue single page applications

I recently developed a Vue.js application using vue-loader and now I am trying to integrate an npm package that I have installed. Here is the code snippet: var x = require('package-name') Vue.use(x) However, I encountered the following ...

What causes a null element in Ruby on Rails?

I am facing an issue with a modal dialog box that contains a search field. Whenever I select an element from the drop-down list, I encounter an error saying "element is null". I cannot seem to figure out why this error is occurring. Below is the code snipp ...

Harnessing the power of service binding in AngularJS

I am utilizing a service to facilitate data sharing between two controllers and retrieve a list of data: myApp.service('DataService', function($http) { this.data = []; this.loadData = function() { $http.get('/api/data') ...

Utilizing JavaScript to Automatically Rename Files in Sharepoint Document Library Based on Content

Hello there! I previously had a feature on a SharePoint document library that successfully copied the name of a file to the title column. However, this functionality ceased to work after an update to the SharePoint platform, and I am struggling to determi ...

Issues with HTML Units not Showing up

I'm trying to achieve the same functionality as this JSFiddle: https://jsfiddle.net/nstruth/t0dopzav/1/ When I select Volvo, the HTML displays correctly but the JavaScript doesn't seem to be functioning. I've looked at other innerHTML JavaS ...

Is it possible to eliminate process.env.NODE_ENV using browserify/envify?

Currently, I am utilizing ReactJS through NPM and Browserify, but I am encountering difficulties while attempting to build it in production mode as mentioned in the readme. The code I have for setting up browserify is: var browserify = require('brows ...

I noticed that when I use jQuery to add a class to an <li> element, the class is added successfully but then quickly removed. I'm wondering if this could be a conflict with

$(document).ready(function() { var $listItems = $('ul li'); listItems.click(function() { $listItems.removeClass('selected'); $(this).addClass('selected'); }); }); .selected{ background color: "green"; } / ...

Is it possible to customize the Toolbar in react-data-grid by adding your own components?

I have been working with the react-data-grid and I'm almost done with it. The filters button is already displaying in the Toolbar, but now I need to add another button that will affect all selected items in the table. I want to place this new button o ...

Customize Your Lightbox Fields with DHXScheduler

In my JSP application for exam timetabling, I have integrated DHXScheduler and customized the lightbox to display additional information about exams using my own fields. The EventsManager class is responsible for managing events by saving, creating, and r ...

Avoid refreshing AJAX on browser back navigation

Describing my current situation: I have a scenario with 2 pages: - On page 1, it sends a request using $.ajax to receive JSON data for display. Then there is a button that when clicked, takes me to page 2. - After clicking the button and transitionin ...