Answer the question
In order to leave comments, you need to log in
How to properly process a put request in SLIM?
Chrome swears like this
Failed to load http://127.0.0.1/api/v1.0/item/1: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
->withJSON(...
Allowed methods: GET, PUT, POST, DELETE, PATCH
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->get("/items/{first}/{amount}", function($request, $response, $args) {
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
->withJSON(
[
"itemsCount" => 1,
"items" => [
[
"id" => 1,
"name" => "Shapka",
"description" => "Description"
],
[
"id" => 2,
"name" => "Zontik",
"description" => "Opisanie zontika"
]
]
],
200,
JSON_UNESCAPED_UNICODE
);
});
$app->put("/item/{id}", function($request, $response, $args) {
return $response
->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
->write("done");
});
// Catch-all route to serve a 404 Not Found page if none of the routes match
// NOTE: make sure this route is defined last
$app->map(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'], '/{routes:.+}', function($req, $res) {
$handler = $this->notFoundHandler; // handle using the default Slim page not found handler
return $handler($req, $res);
});
$app->run();
?>
updateItem(item) {
console.log("update item id: ", item)
let xhr = new XMLHttpRequest()
xhr.open("PUT", `http://127.0.0.1/api/v1.0/item/${item.id}`)
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
xhr.send("{\"name\":\"azaza\"}")
this.updateItemsFromRestApi()
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question