让我展示一个不使用NodeJs的例子
首先,你需要安装NelmioCorsbundle
和FosRestbundle
,然后像这样配置它们:
nelmio_cors:
paths:
'^/':
origin_regex: true
allow_origin: [ 'http://your-domain.com' ] << your frontend
allow_headers: ['Origin','Accept','Content-Type']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600
hosts:
- "^(http?://)?api\.your-domain.com?" << your backend as subdomain
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
view_response_listener: 'force'
yourApp.factory('appService', ['$http', '$q', '$localStorage',
function($http, $q, $localStorage)
{
var $this = {};
$this.mainGetter = function(action, config) {
var deferred = $q.defer();
$http({
method: 'GET',
url: $this.domain + action,
params: config
}).then(function(data) {
deferred.resolve(data);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
};
return $this;
}]);
/**
* API Controller
* @CFG\Route("/api")
*/
class ApiController extends FOSRestController
{
/**
* @CFG\Route("/get-something", name="get_smt")
* @CFG\Method("GET")
* @param Request $request
* @return JsonResponse
*/
public function getPostsAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$something = $em->getRepository('SomeRepo')->findAll();
$serializer = $this->get('jms_serializer');
return new JsonResponse([
'isError' => 0,
'data' => $serializer->serialize($something, 'json')
]);
}
};
$this.getApiData = function(alias) {
var deferred = $q.defer();
appService.mainGetter('/get-something', {})
.then(function(response) {
var data = response.data;
if (data.isError) {
deferred.reject(data.error);
} else {
deferred.resolve(data.data);
}
});
return deferred.promise;
};
好的,谢谢D.Dimitrioglo最后的评论,“这只是一个通知,不是错误,请不要关注它”,所以我没有花时间去弄清楚为什么我的主机不支持。不过我需要nodejs来将我使用的TypeScript编译成JavaScript,所以那不是问题所在。此外,我并不明确需要NelmioCorseBundle和FosRestBundle。我的问题是
之后我的会话在登录后得以保留!感谢您的评论,它引导我朝着正确的方向前进!