Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  28] [ 2]  / answers: 1 / hits: 16961  / 8 Years ago, fri, june 24, 2016, 12:00:00

I built an API with the SLIM Micro-Framework. I setup some middleware that adds the CORS headers using the following code.



class Cors{

public function __invoke(Request $request, Response $response, $next){

$response = $next($request, $response);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}

}


For my front-end, I used VueJS. I setup VueResource and created a function with the following code.



register (context, email, password) {
Vue.http({
url: 'api/auth/register',
method: 'POST',
data: {
email: email,
password: password
}
}).then(response => {
context.success = true
}, response => {
context.response = response.data
context.error = true
})
}


In chrome, the following error is logged to the console.



XMLHttpRequest cannot load http://mysite:9800/api/auth/register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite' is therefore not allowed access.


Oddly enough, GET requests work perfectly.


More From » cors

 Answers
5

You half 1/2 the solution here.



What you are missing is an OPTIONS route where these headers need to be added as well.



$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});

[#61659] Wednesday, June 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
elishaannac questions
Sun, Dec 5, 21, 00:00, 3 Years ago
Mon, Jun 14, 21, 00:00, 3 Years ago
Mon, Jul 22, 19, 00:00, 5 Years ago
Mon, Jul 8, 19, 00:00, 5 Years ago
;