大家好,我尝试使用由FOSRest软件包(symofony 3)制作的API,该软件包在本地(localhost:8000 / api / projects)工作。我想使用Axios通过VueJS获取数据
// VueJS调用
axios
.get('http://localhost:8000/api/projects/2')
.then(response => (console.log(response)))
.catch(function (error) {
console.log(error);
});
如您所见,我还安装了cors npm库
我遇到此错误,我不知道如何解决此问题
xhr.js?ec6c:178已从CORS策略阻止从源“ http://localhost:8080”访问“ localhost:8000 / api / projects / 2”处的XMLHttpRequest:仅协议方案支持跨源请求:http,数据,chrome,chrome扩展名,https。
我决定将NelmioCorsBundle用于symfony,你能告诉我是否做错了
// app / config / config.yml
nelmio_cors:
paths:
'^/api/':
allow_origin: ['*']
allow_headers: ['X-Custom-Auth', 'Content-Type', 'Authorization']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600
// app / AppKernel.php
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
new Sonata\CoreBundle\SonataCoreBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new Sonata\AdminBundle\SonataAdminBundle(),
new FOS\UserBundle\FOSUserBundle(),
new FOS\RestBundle\FOSRestBundle(),
new Nelmio\CorsBundle\NelmioCorsBundle(),
new UserBundle\UserBundle(),
];
请帮助我了解我的代码中有什么不好的地方,谢谢!
解决方案
// ProjectController.php
/* $formatted is an array which make request to the database */
$formatted = [
'id' => $project->getId(),
'title' => $project->getTitleProj(),
'link' => $project->getLinkProj(),
'desc' => $project->getDescProj(),
'members' => $members,
'skills' => $skills,
'context' => $context,
];
$response = new JsonResponse( $formatted );
// resolve problem
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
// VueJS
axios
.get('http://localhost:8000/api/projects/2')
.then(response => (console.log(response)))
.catch(function (error) {
console.log(error);
});