📜  wordpress cors request 400 bad request rest (1)

📅  最后修改于: 2023-12-03 15:35:43.472000             🧑  作者: Mango

WordPress CORS Request 400 Bad Request REST

Introduction

In WordPress, the REST API allows developers to access and update site data using HTTP requests. When working on a site, developers may encounter issues with these requests and receive a 400 Bad Request error message. This error can be attributed to a problem with Cross-Origin Resource Sharing (CORS).

What is CORS?

Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent requests from resources outside of the current domain. When making a request, the browser automatically includes an Origin header with the domain of the requesting site. If the server does not allow requests from this domain, the browser will block the request, resulting in a 400 Bad Request error.

How to Fix CORS Issues

To fix CORS issues in WordPress, developers must allow requests from outside domains. This can be done by adding code to the site's functions.php file or by using a plugin.

Functions.php

To allow CORS requests in the functions.php file, add the following code:

function allow_cors() {
   header("Access-Control-Allow-Origin: *");
   header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
   header("Access-Control-Allow-Headers: content-type, authorization");
}
add_action('init', 'allow_cors');

This code adds the necessary headers to allow requests from any domain.

Plugin

Using a plugin to fix CORS issues is an easier option for non-developers. One such plugin is the Enable CORS plugin. This plugin adds the required headers to allow CORS requests on the site.

Conclusion

In summary, the 400 Bad Request error in WordPress REST API is often due to a CORS issue. Developers can fix this by allowing requests from outside domains using code or a plugin. By fixing these issues, your WordPress site's REST API will function properly and allow for seamless communication with other sites and applications.