简体   繁体   中英

“405 Method Not Allowed” error while trying to send req. via JS fetch API to PHP file

I'm trying to use PUT, PATCH, UPDATE etc. methods on my project to learn how REST works.

I used JS fetch API to send requests and I got "405 Method Not Allowed" error. I searched it then changed my .htaccess to this:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "*"
Header add Access-Control-Allow-Methods "GET, PUT, POST, UPDATE, DELETE, OPTIONS"

I used that website to check if all headers are correct:
https://www.webconfs.com/http-header-check.php

result is:

HTTP/1.1 200 OK => 
Date => Mon, 01 Jul 2019 14:36:58 GMT
Server => Apache/2
X-Powered-By => PHP/5.6.40
Cache-Control => max-age=2592000
Expires => Wed, 31 Jul 2019 14:36:58 GMT
Vary => Accept-Encoding,User-Agent
Access-Control-Allow-Origin => *
Access-Control-Allow-Headers => *
Access-Control-Allow-Methods => GET, PUT, POST, UPDATE, DELETE, OPTIONS
Connection => close
Content-Type => text/html; charset=UTF-8

Result contains

Access-Control-Allow-Methods => GET, PUT, POST, UPDATE, DELETE, OPTIONS

and JS XHR still gives 405 error.

What is the problem? Thank you for your answers.

You are conflating two different issues here.

You have an HTTP 405 Method Not Allowed Response , which means that the server is rejecting whatever HTTP method you are using to make the request.

You are conflating it with the Same Origin Policy, which is enforced by the browser to stop JavaScript on a malicious website from using the browser to get access to secret data on a different website (eg your webmail service).

If it was a Same Origin Policy issue then the browser console would display a message about CORS or Access-Control headers in the Console of the Developer Tools.

In this case whatever method you are using (and you've said "PUT, PATCH, UPDATE etc", which is quite broad) isn't supported by the server. Note that, by default, when dealing with static files, most servers only allow GET, POST, OPTIONS, and HEAD requests.

You generally need to write server-side code to process other kinds of requests and servers don't generally have any default handling built in at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM