Changet POST to Delete - javascript

I Changed a http method POST to DELETE and when i click a button nothing happens.
what i have but works
router.post('/', function(req, res) {
//do something
});
what i want
router.delete('/', function(req, res) {
//do something
});

The important thing to remember when defining your server side routes is that even though two route definitions may have the same path but different HTTP verbs, they are not treated as the same by the RESTful API infrastructure. It is essentially like defining two completely separate functions in a class. The POST route will only ever be called if a POST request is sent to the applicable route, while the DELETE route will only ever be called if a DELETE request is sent to the applicable route. The execution of those two different route definitions is completely dependent on the HTTP verb that is specified in the HTTP request object that is sent to your API. You can read about all of the different HTTP request methods here.
Without being able to see the code for your button, all I can say is that in order to fix your broken code, you need to make sure that your HTTP request that is being sent to the server is specifying a DELETE HTTP verb instead of the original POST HTTP verb that your code was originally specifying when your code initially worked.

Related

What’s the difference between res.send and app.post?

I’m new to express and HTTP. The express library has app.get, app.post and res.send. As I understand it, app.get uses/is used with GET and app.post POST. Does res.send call POST?
res.send() sends a response to an incoming http request that has come into your http server.
app.post() registers a request handler with Express for a specific URL in your http server and for POST requests so that when your Express server receives a POST request at that URL, it will call this request handler.
Here's an example of res.send():
// configure request handler for GET request to /
app.get("/", (req, res) => {
res.send("hi"); // send response to incoming http request
});
Here's an example of app.post():
// this middleware reads and parses the body for content-type
// of application/x-www-form-urlencoded
app.use(express.urlencoded({extended: true}));
// configure request handler for POST request to /login
app.post("/login", (req, res) => {
// in a real request handler, this would be some sort of username
// and password comparison in a database and using appropriate crypto
if (req.body.username === "John" && req.body.password === "foobar99") {
res.send("login successful");
} else {
res.status(401).send("Login failed");
}
});
The express library has res.get and res.send. As I understand it, res.get uses / is used with GET.
You are perhaps confused because there is no res.get. Perhaps you meant app.get()? If so, app.get() configures a request handler for an http GET request to a specific URL. So, app.get("/books", ...) might display a page of all available books.
Does res.send call POST?
No. res.send() sends a response to an http request.
Here are the steps you can think of.
An http client (such as a browser or any piece of code) creates an http request and sends that request to a server.
That request will have both an HTTP verb such as GET, POST, PATCH, etc... and it will have a URL such as /login or /books.
The web server that the request was sent to receives that request. In the case of a web server using the Express framework, the Express server looks through its list of already registered routes (these routes were previously registered with app.get(...), app.post(...), app.use(...), etc... These are essentially listeners for specific routes. If the Express server finds an already registered route that matches both the http request verb and the URL, then it calls that route handler and pass it three arguments (req, res, next).
When the request handler code gets called, it can examine the req object to see any data about the incoming request such as the exact URL, any http headers on the request and so on. It can use the res object for sending a response such as setting any http headers on the response, setting content-type, setting an http status code for the response, creating and sending the body of the response, etc... res.send() is one way to send the response. There are also others such as res.sendFile(), res.json(), res.sendStatus() and so on...
After one of these methods is called that sends the response, then the underlying engine sends that http response back to the client that sent the original http request and the HTTP request/response is considered complete.
Those are two different modules/objects..
The Express Router supports HTTP methods for the server to listens and respond to - .get(), .post(), .put().
One of the arguments passed through the chain of middleware and handlers is the Response, which has a .send() method to send its response back to the client. The Response object can also be enhanced to send JSON, etc.

can someone please explain REQ in express plz

I dont get how we use req in express. I undrstand that the server can respond back to client,but when it comes to req object im confused. Is req when the server is asking for somethong from the client?
HTTP is an application, client-server protocol. Everytime that a client want the server to perform an action, it has to make a request. The HTTP protocol defines a set of actions or verbs that are available to the client so it can make each request using one specific verb (GET, POST, PATCH, PUT, DELETE, etc). It doesn't matter what verb the client uses, only the client can initiate a comunication with the server using one of that verbs. So this is how exactly an HTTP GET request looks like:
GET / HTTP/1.1
Host: example.com
User-Agent: curl/7.69.1
Accept: */*
The first line contains the verb used, in this case GET, the path requested, in this case /, and the protocol version, in this case HTTP/1.1. The next lines, are a set of key value pairs called the headers of that request, which can define a lot of aspects of the request made by the client to the server. By the way, an HTTP server never could or will start a request to a client, a client always is the one that make the request, and the server is always the one that response that request. One of the aspects of that request for example, is the destination host, that is present in the header host with the value of example.com. Bellow of the headers, all the HTTP requests have a blank line and then the body of the request, which normally contains the data that is sent from the client to the server. In this case, no data body is sent on the request.
Express is an HTTP server based on the HTTP module available on Node.js. Express simplifies the way that the native Node.js HTTP server works. Here is tipically how an Express app looks like:
const express = require('express');
const app = express();
// This is called a router
app.get('/path', (req, res) => {
// This router will perform some action with the req object
// And will send a response to the client
});
So, on the example above, the method app.get(...), available on Express applications, allows the server to deal with the GET requests that come from the client. The app.get() method takes two arguments, a path and a callback function. The path argument represent the string that goes after the name server, for example, in the URL www.example.com/test, the hostname is www.example.com, and the path is /test. That method app.get() is also called a Router. So, the router of the example will deal with the GET requests to that server which also define /path value as the path the request is sent to. Once a request to the server fit those two conditions, that callback will be triggered.
So, finally we get to the answer. The res variable is an object (a set of key-pair values separated by commas and locked into curly braces), that contains the data of the HTTP request, into a friendly legible object. For example, if you want to print to the console the path that the client used, you can print it like this console.log(req.path), or you can get all the headers of that HTTP request, you can use console.log(req.headers). The req object is one of the 5 main objects in Express, in fact the Express documentation defines a ton of methods that you can use with the request object (req). To get deep into the request object, you can see the official Express documentation in this link. The callback defined into the router, can use the req object, to extract information of the client's request, process it and return a response to the client later.
With an express server, you get two objects passed to a request handler.
req is data about the incoming request (things that were sent from the client). It contains the headers on the request, it contains a parsed query string, it contains the URL path, it's generally the object where middleware puts things for request handlers to use. While Express adds a bit more to this object, you can see the general concept of the req object by looking and the http.IncomingMessage object documented here. This is what the object starts out as and then Express adds more to it. The express version of the object is documented here.
res is the response object. This is all about sending a response. It will hold the outbound headers you want to send with the request. It contains the methods you use for sending a response. The core object is an http.ServerResponse object documented here and then Express adds some more things to the object on top of that which is document here.

React JS + React Router works with $.get but not $.ajax PUT

I've got a react.js setup and I've got some simple routes using react-router. I have a dispatcher:
import dispatcher from "../dispatcher";
export function reloadList(){
dispatcher.dispatch({type: "FETCH_LIST"});
let serverRequest = $.get("../../data/list.json",
function(data){
console.log(data); //Logs correct data from list.json
}
);
}
export function saveList(list){
dispatcher.dispatch({type: "SAVE_LIST"});
let serverRequest =
$.ajax(
url: "../../data/list.json",
dataType: 'json',
method: 'PUT',
data: list,
success: function(data) {
console.log("success!"); //does not output
},
error: function(xhr, status, err) {
console.log(status, err.toString()); //outputs a 404 error
}
});
)
}
The reloadList() function runs fine and outputs the JSON data. The saveList() function throws a 404 error. I'm assuming this is because of the way the app handles routes, but I'm confused as to why it works with get and not put (or post for that matter).
I've been struggling with saving data to a file in react, this seemed like the right way at first but now I'm not so sure. Is there something I'm doing wrong here?
I'm going to assume based on your phrasing, that you're using some sort of simple HTTP server (or no server at all) for developing locally, and list.json is a file on your machine. If this is the case, your issue is that your HTTP server doesn't have the routing to know how to handle PUTs (or POSTs, or probably any method other than GET for that matter). If you want to write files to your system you will need to add an actual backend that can handle a PUT and more intelligently interact with the filesystem.
Unfortunately there's no simple way to write files to disk in the browser alone (for security reasons), but if you want to avoid adding to your backend, you could look into creating files for download using a Blob
You can't change the contents of a file on the server from the browser using only an ajax request. Think about how terribly insecure the internet would be if I could change files on your server just by sending an ajax request.
You're going to need some server side code that can handle such a request. For instance, you can setups a simple Node / Express server that has a route which can handle reading and writing to disk, using the built in fs module.
Maybe later on you'll want to use a database instead.
http://expressjs.com/en/starter/installing.html
Make sure your server routes the PUT request, not just GET.
For example express.js routes like this:
`app.get("/getRequestHere",function(){});
app.put("/putRequestHere",function(){});`
Some browsers (Chrome) restrict the ability to make PUT/DELETE requests. It sents out an OPTION request that returns 404. What you want to do is put this in your .htaccess file:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token, accessToken"
# Added a rewrite to respond with a 200 SUCCESS on every OPTIONS request.
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
first parts accepts access for PUT methods,
second part forwards (rewrite) OPTION method requests into an 200 response. This code I copied somewhere else on stackoverflow and it totally works.
(stop down voting me guys. This answer totally works)

How to redirect user to login page when session token expired?

I have Marionette + Node application.
When token expires the app does not react and user is not redirects to the LogIn page.
My question is - how to listen for session token status from Node?
Good day to you sir. Let me give you a quick intro to request handlers, endpoints, and middleware.
Express.js is very common request handler. Request handlers, do what they sound like they do. They handle requests; more specifically http requests. You can find plenty of examples online on how to create basic endpoints with express.js.
Now on to the more important part, middleware. In express at least middleware is software that's inserted between the arriving request, and the end point it was meant to reach.
I will use Express syntax.
Say I have an endpoint foo:
Router.get('/foo', function(req, res) {});
However this endpoint should only be accessible under certain conditions. So I insert a middleware right in that request handler definition:
Router.get('/foo', function iAmAMiddleware(req, res, next) {
Here you can implement any logic you want. you have access to
the request, and the response. Meaning that if something in wrong
in the request, then you can return a response from here like
res.send(404);
BUT if all checks out all you have to do is call next() and
the flow will continue into the actual handler function.
},
function iAmTheEndpointHandler(req, res) {})
Usage of middleware is huge. Google express middleware and you'll find plenty of information.
Good luck to you.

Express.JS: Attach cookie to statically served content

I use Express.JS to serve static content:
express.use(express.static('./../'));
When index.html is served, I would like to send a cookie alongside the response indicating if the user is signed in or not. Normally one should use res.cookie() but I cannot see how to use it for statically served content.
Not sure why you need to do this, but you can place your own middleware before the static module.
The following quick hack should work:
function attach_cookie(url, cookie, value) {
return function(req, res, next) {
if (req.url == url) {
res.cookie(cookie, value);
}
next();
}
}
app.configure(function(){
app.use(attach_cookie('/index.html', 'mycookie', 'value'));
app.use(express.static(path.join(__dirname, 'public')));
});
The above inserts another function in the chain of middleware express uses before the static middleware. The new layer attaches the cookie to the response if the URL matches the specific one you are looking for -- and passes the response further down the chain.
Consider also the following approach:
If your express is behind web-server you can serve static files without bothering express - it should be faster than via middle-ware. If you use nginx, this can help: Nginx Reverse Proxying to Node.js with Rewrite.
Assuming that your static file has javascript in it, you can also set cookies directly on the client side only requesting from express the data you need for this cookie:
document.cookie = "user_id=" + user_id;
Flanagan's JS definitive guide (edition 6!) has an excellent coverage on how to use cookies in client-side javascript (in addition to being the best among JavaScript books :).
It can be a trivial advice, but I have seen the following flow (more than once): client sends API request (which has a cookie attached to it, obviously), server gets data from the cookie and serves the response completely built on the data contained in this cookie. All this instead of just quietly reading this cookie in the client. Basically client asks the server what it has in its own cookie.
In your scenario you need to request user_id/access_key only once and then always check the cookie in the client, going to the server only for the data that client doesn't already have, but storing and checking session state and, maybe, some compact data used in most pages (such as username, e.g.) in cookies locally (you can also cache data in local storage, to reduce the server load even further). In this case, express won't even know if a user accidentally refreshes the page (if you don't change URLs to reflect application state as well, of course, or only change #-part).
As app.configure was removed since Express.js v4, I would like to do an update.
For Express.js versions > 4, to initialise my app by passing options inside the express.static(root, [options]) method, in which you can pass a Set-Cookie header in the property called setHeaders:
app.use(express.static(publicPath, {
setHeaders: function (res, path, stat) {
res.set('Set-Cookie', "myCookie=cookieValue;Path=/")
}
}));
It is important to set Path=/ because otherwise express will create numerous duplicates of the cookie on the client side.

Categories

Resources