Transitioning from a traditional CURL method to utilizing AJAX and XMLHttp

I'm currently facing a challenge converting the curl code from an API named TextRazor to AJAX XMLHttp due to limitations on the platform I am working with. Despite trying various solutions shared by the community, I have been unsuccessful in retrieving any data, only receiving a "400: Bad Request" error. For reference, here is how the API call should be made based on the documentation:

curl -X POST \
-H "x-textrazor-key: YOUR_API_KEY" \
-d "extractors=entities,entailments" \
-d "text=Spain's stricken Bankia expects to sell off..." \
https://api.textrazor.com/

My current implementation of AJAX XMLHttp code appears as follows:

var xhttp = new XMLHttpRequest();
var url = "https://api.textrazor.com/";
var params = "extractors=entities&text=Spain's stricken Bankia expects to sell...";
xhttp.open("POST", url, true);

xhttp.setRequestHeader("x-textrazor-key", "YOUR_API_KEY");
xhttp.setRequestHeader("Content-length", params.length);

xhttp.onreadystatechange = function() {
if(xhttp.readyState == 4 && xhttp.status == 200) {
    alert(xhttp.responseText);
}
}

xhttp.send(params);

Your assistance is greatly appreciated!

Answer №1

You've encountered the issue of the same origin policy.

When making a cross-origin request with a custom header, the browser initiates a preflight OPTIONS request before proceeding with your intended request.

The server you're trying to reach isn't configured to handle OPTIONS requests, resulting in a 400 error being returned.

To resolve this:

  • Ensure that CORS is supported by the server
  • If possible, use alternative methods like JSONP (although not recommended due to availability of CORS)
  • Avoid making direct requests to their server from the browser

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

"Step-by-step guide on using JavaScript to print a PDF file stored locally

As an illustration, I have a local PDF file with 6 pages. When using the window.print() function, only one page is displayed in print preview regardless of what is shown in the browser. Instead of just one page, all pages should be visible in print previ ...

The issue with Array.prototype.join in Internet Explorer 8

In my current working scenario, I encountered an issue with the following code snippet. It performs well in the latest versions of Internet Explorer (IE), but the join function fails to work correctly in IE 8 Version. <!DOCTYPE html> <html xmlns= ...

"Facing an issue with Google Chrome not refreshing the latest options in an HTML select dropdown list

Having trouble creating an offline HTML file that incorporates jQuery for the script. The page features a state select menu followed by a second menu for counties. When a state is selected, only the corresponding counties should display while others remai ...

I am currently struggling with the mapquest GeoJson integration within my Node/Express application. I keep encountering an error message that reads "body used already."

I attempted to utilize the mapquest API by following the provided documentation, however I encountered an error message: HttpError: body used already for: Below is my geoCoder.js configuration: const NodeGeocoder = require('node-geocoder'); con ...

Error message: The Modelviewer is unable to load the local file, displaying the message "Unauthorized to access local resource."

For my WebAR project, I am utilizing Google's ModelViewer. In my vue.js project, I have a component that loads the model using the <model-viewer> attribute. My goal is to set the src attribute of the model-viewer to the absolute path of the .gl ...

Ensuring Package Security in NodeJS and NPM

Given the immense popularity of NodeJS and how NPM operates, what measures can be taken to prevent the installation of insecure or malware-laden packages? Relying solely on user feedback from sources like StackOverflow or personal blogs seems to leave a si ...

The conversion from JSON to a PHP API is facing obstacles

I'm having an issue with saving data when a button is clicked using Javascript and PHP. Button click: var xhr = new XMLHttpRequest(); var url = "savedata.php"; xhr.open("POST", url, true); xhr.setReque ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

issue with splice function

I have a JavaScript function that is supposed to collect all input values from text boxes and store them in an array. However, I want to remove any input value with the type "button" from the array before proceeding. Here is the code snippet: <!-- lang ...

Tips for triggering jquery code when a variable containing a CSS attribute is modified

I have a specific requirement where I need to reset the scrollleft value to 0 on my wrapper whenever a particular CSS property changes. Although I am new to using jQuery and haven't worked with variables much, I believe I need to create a variable to ...

Executing Node.js Function from an External File Dynamically

Is it possible to run a Node function from an external file that may be subject to change? main.js function read_external(){ var external = require('./external.js'); var result = external.result(); console.log(result); } setInterva ...

Determine if a radio button is selected using Jquery

I am currently working on a script that should uncheck a radio button if it is checked, and vice versa. However, I'm facing an issue where the script always registers the radio button as checked even when it's not. Below is the code snippet in q ...

Struggling with loading.jsx file in next js version 13.4.5?

Encountered an issue with loading components in next js 13.4.5 layout.jsx "use client"; import React, { Suspense } from "react"; import { ThemeProvider, createTheme } from "@mui/material/styles"; import CssBaseline from " ...

detect and handle errors when deploying the Node.js function

I'm currently attempting to use code I found on Github to insert data into a Firestore database, but unfortunately, I keep encountering an error. Here's the specific error message: 21:1 error Expected catch() or return promise/catch-or-re ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

When running the `mocha` command with `npm test`, no specific

Could use some help: I've encountered an issue while running a unit-testing command. The error messages are not being printed when there are errors, making debugging quite challenging. Here is the command I executed: and here's the package.json ...

Error encountered in MEAN stack when making an AJAX POST request: TypeError occurs when attempting to access property 'userName' of an undefined object

Currently, I am involved in the development of a MEAN stack application for my school project. The main objective is to allow users to view and submit highscores for Galaga and Dig Dug games to a MongoDB database. An issue that I am facing is: POST http ...

Could someone share an instance of an AngularJS configuration that continuously checks for new data and automatically refreshes the user interface once the data is obtained?

Struggling to find a suitable example for this scenario. I am looking to create a chart directive that will be updated every minute by fetching data from a web service. Currently, I have a service that acts as a wrapper for the web service. My controller ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...