MEAN.js $http.get() return index html content instead of json file - meanjs

I'm doing a web app based on original MEAN.js framework. When I want to request local json test file using $http.get() method in my AngularJS file, it returned my index html content.Is it a routing problem? I didnot change the original mean.js routing code(https://github.com/meanjs/mean), just added a $http.get() method in home.client.controller.js file. Can anyone help me with this? Thanks!

That is most likely happening, because you didn't define an endpoint for that particular GET request in your app.
Everytime you make a request to your server (for example a GET request to /my-request) nodejs/express are configured in MEAN.js so that your server will try to find the endpoint for that request, if it does not find any, that request will be handled by this particular code block (specified in /modules/core/server/routes/core.server.routes.js):
// Define application route
app.route('/*').get(core.renderIndex);
Which will basically render the index view.
I'm not sure if you're using a custom module or not, eitherway, if you want that request to be handled in a different way in MEAN.js, you can specify your endpoint in your custom module routes file (or in core.server.controller.js) like so:
// Define application route
app.route('/my-request').get(core.sendMyJSON);
Be careful, because this route must be placed before the one I mentioned earlier, otherwise your request will still be handled the same way and the index view will be rendered and served again.
Then you will have to create the controller that should be called to handle that request:
exports.sendMyJSON = function (req, res) {
// logic to serve the JSON file
};
This way you should be able to get it done with a few adjustments.
Side note:
I'm not entirely sure but I think if you place your JSON file in the public directory of your app you should be able to directly access it without the need for the extra logic.

Related

How to make RESTful routes in Cake3 without using extensions?

I want to make a RESTful API in my CakePHP application however, the only way it describes is using extensions (a.k.a file extensions) https://book.cakephp.org/3.0/en/development/routing.html#creating-restful-routes but this isn't feasible for me considering that I actually have JSON files that I do not wish to get confused with CakePHP, not only that but adding .json or whatever to the end of a path is likely to be missed and omitting it does not change that it will actually go there causing an error to show.
Is there a way to create RESTful routes without using extensions?
Extensions are optional
Extensions are by no means required for RESTful routes to work. Extensions are part of how the request handler component configures the rendering and response process, the routes themselves will work just fine without specifying extensions.
It looks like the docs are kind of outdated, the sentence describing the code example doesn't make any sense:
The first line sets up a number of default routes for easy REST access where method specifies the desired result format (e.g. xml, json, rss). These routes are HTTP Request Method sensitive.
I guess this belongs to an older code example. You may want to report this over at GitHub.
Use the Accept header
That being said, the request handler component also evaluates the Accept header, so you could make sending application/json the requirement for your API.
Also if you don't want to accept non-JSON requests at all, then you should check Request::is() and throw an exception accordingly.
if (!$this->request->is('json')) {
throw new \Cake\Network\Exception\BadRequestException():
}
Hardcode the components behavior
Furthermore it's possible to overwrite the extension that the request handler determines, and make the component think this is a JSON request:
$this->RequestHandler->ext = 'json';
It should be noted that this won't affect methods like RequestHandler::prefers()!
And finally you can also use the RequestHandler::renderAs() method to tell the request handler how to render and respond:
$this->RequestHandler->renderAs($this, 'json');
This however would need to be done in the Controller.beforeRender event in order to override the components behavior in case it identifies a request of a type that it is normally ment to handle.
See also
Cookbook > Controllers > Request & Response Objects > Checking Request Conditions
Cookbook > Controllers > Components > Request Handling > Responding To Requests
API > \Cake\Controller\Component\RequestHandlerComponent::$ext

How to serve static (or dynamic?) HTML files with RESTful API?

Hi I'm studying about RESTful API and making a website running on local to exercise.
I think RESTful is a quite good way. CRUD operations can be identified by HTTP methods and we can handle them with one url.
But most confusing things to me is that, How can we serve HTML files which are needed to request CRUD operations?
For example, If I'm implementing a forum, I need APIs to CRUD posts in forum like
[GET] /forum - see all posts in forum
[POST] /forum - create a new post
[GET] /forum/:id - see the post of id
[PUT] /forum/:id - modify the post of id
[DELETE] /forum/:id - delete the post of id
Think about how we use a forum, we need at least 3 type of HTML pages.
They are,
1. a page to see all posts in forum.
2. a page to see the specific post.
3. a page to type title and contents to create(or modify) a new post.
First and second type of HTML files can be served easily by GET requests above.
But in case of third type HTML files, I need to use extra parameters with above APIs or make a new API such like /forum/createpost to serve such HTML files.
I think, in the point of view of RESTful, I miss something and need to distinguish serving static (or dynamic) HTMLs and handling CRUD requests.
What is the bestpractices to handle this problem?
I also find some questions about this problem, but I couldn't find a clear answer.
I think you are mixing up two separate parts of the application. One is the REST API that provides the endpoints for CRUD operations. The HTML files that send the API requests are not part of the REST API. They are served by a web application that provides the front-end to the user, and makes calls to the REST API in the backend to fetch the information to display. To put it in another way, the web application making the calls is your Presentation layer. The REST API is your Business logic. Presumably, the REST API interacts with a database to write data to and read data from it. That is your Persistence or Storage layer.
You can use HTTP content type negotiation for that. POST/PUT requests (can) contain a Content-Type header declaring the type of content they're sending, and—more importantly—all requests contain an Accept header declaring the kinds of responses it accepts. If the client is accepting text/html responses, serve an HTML page; if they're accepting, say, application/json responses, serve a "RESTful" JSON response. This way your server can respond to different situations with the appropriate content and the same endpoint can serve as API and as HTML handler.
Alternatively, you can distinguish the request by using an extension: /posts.html serves a plain HTML file, while /posts gets served by a REST endpoint. That can easily be done in the web server configuration.
This might or might not be an anwser to your problem, however since you're working in Node + Express, routing might be a way to go (If I understood your question correctly). Below is an example of server implementation of accepted routes with parameters. Note, you can make parameters optional in some cases if needed.
app.get('/', function (req, res) {
res.send('Index')
})
app.get('/forum', function (req, res) {
res.send('Forum Index')
})
app.get('/forum/:id', function (req, res) {
// To access id you do 'req.params.id'
res.send('Forum Index')
})
app.put('/forum/:id', function (req, res) {
res.send('Modify Forum')
})
app.delete('/forum/:id', function (req, res) {
res.send('Delete Forum')
})
Reference : https://expressjs.com/en/guide/routing.html

ReactJS + Redux: Why getting 'POST' net::ERR_CONNECTION_REFUSED?

I am following https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/ at the moment, and I pretty much did the same, yet I am still getting the following error:
Is http://localhost:3001/sessions/create down? If not, what may be the cause of the error?
Thank you in advance!
EDIT
I set up my Express to port 3000 as well, just like how it is shown in the tutorial and used the same API url.
Issue could be because you are not setting a base URL in the API calls.
For example, if you are using Auth0 as a service, then API URL in requests must be as below,
axios.post('https://your.auth0.url/sessions/create', data);
(Assuming that you are using axios)
I suppose the current configuration is as below,
axios.post('/sessions/create', data);
and it takes the relative URL and it will be from the app serving the rendering of base page, in your case that is localhost:3001
It is advised to keep the base url (http://auth0.your.url) as an environment variable and can be supplied while running the app.
If you are using webpack take a look at Webpack define plugin also.

call and render a controller method in laravel without a redirect

Background
laravel currently allows you to easily define views for specific HTTP status code responses. For example, an HTTP status code of 404 will display the resources/views/errors/404.blade.php view automatically if it exists. it works the same for other codes like 500 errors.
Problem
All of the routes on my site are processed through controllers, all of which extend a base Controller. This base controller sometimes initializes the user, sets the current timezone, and other random stuff. The master template often relies on these variables. For example, if a user is logged in, the Controller figures that out and passes that user to the view. My master template looks for that user, and shows certain functionality if present. When a 404 is hit, I want to still be able to show the user specific menus, and continue using that 404 view.
Question
I submitted an issue on Github to see if we could route HTTP exceptions through controllers, but they did not agree with the proposal. So now I'm looking to see if there is a way to render a controller method when I catch an HTTP exception. I do not want to simply redirect to the appropriate route, but rather catch the exception and render the controller method.
I don't know enough about the internals of the routing, so I'm curious, is this possible? And if so, how do I do it?
Thanks!
It's definitely possible - look into the ExceptionHandler (under app\Exceptions), or look at implementing some Middleware to catch unknown routes.
Alternatively you can also extend the 404 view from your base template, save data in the session to present on the view or even call a ->back() on the 404 with a flash error.

Preventing default views with RESTful api in CakePHP

I am following the tutorial in the CakePHP book that explains the basics of setting up a RESTful web service.
So far, I've updated my routes file to the following:
Router::mapResources('stores');
Router::parseExtensions('json');
I have also setup a blank layout in app/layouts/json and the appropriate json views. I am receiving my json output successfully when I navigate to controller/action.json
I am wondering though, without the.json extension it attempts to load the regular view. I am looking to build a pure api with only json output, is there any way to prevent regular render output instead?
You could force a rendering as JSON if you can recognise a JSON request another way. For example, if the Accepts HTTP header contains application/json, you could put this in your controller:
public function beforeFilter(){
if ($this->request->accepts('application/json')) {
$this->RequestHandler->renderAs($this, 'json');
}
parent::beforeFilter();
}
It's CakePHP 2.0 notation, but something similar probably exists for CakePHP 1.2 and 1.3.
You could also detect the request Content-Type instead, or as well, especially if Accepts is not used.
What are you seeing at the moment? If you've used bake Cake may have generated the views for you?
Just delete the views in /app/views/layout and /app/views/controllername
If you are trying to prevent the request from hitting the controller at all then I'm not so sure, you could just update your .htaccess file to only send requests ending in .json to the app or something similar.
here is what i did.
if i know i'm building only json API, i added to my AppController.php following:
public function beforeFilter()
{
if (empty($this->request->params['ext']) || $this->request->params['ext'] != "json")
{
$this->render(FALSE, 'maintenance'); //no view, only layout
$this->response->send();
$this->_stop();
}
}
and in my /app/Layouts/maintenance.ctp
echo __('Invalid extension');
this way all requests without the json extension will end up on the "maintenance" page where you can put any info you want, i'm planning to put there link to API docs.