1

I'm writing a simple api for training using express. Here's my testing code:

var express = require('express');
var app = express();
app.post("/api/:var_name", function(req, res) {
    res.send(req.params.var_name);
});

is simply testing to see if POST is working. When I call http://localhost:3000/api/1 I get Cannot GET /api/1, so the server is obviously interpreting the POST request as GET, what do I need to do to call POST instead?

bli00
  • 2,215
  • 2
  • 19
  • 46
  • All urls typed into the browser URL bar are GET requests. To make a POST, you need to either submit an HTML form (can be done entirely from HTML with a submit button) or you can use Javascript to send a POST request. You will typically also need to format and send the POST data too. – jfriend00 Mar 10 '18 at 19:28

2 Answers2

1

Anything you call in the address bar of your browser will be sent via get. This is due to the fact that post-messages (and almost all other methods) do have a body-part. But there is no way for your browser to send additional information inside the body of the http packet.

If you want to test your routes for any method other than GET I would suggest you download a tool like postman.

https://www.getpostman.com/

BEWARE: This is my preference. You can of curse also use text based browsers like curl to test it.

evayly
  • 832
  • 7
  • 18
0

The server interprets the request according to the verb you set in the HTTP request. If no method/verb is specified it is interpreted as GET(not sure about this part).

When you call that URL, you need to use the method as well. For example if you use the fetch API, you can call it like:

fetch(url, {method:"POST"})

If you're entering it in your browser and expect it to be interpreted as a post request, it's not. All browser url requests are GET. Use a tool like Postman to call different HTTP verbs. It's really useful when creating such APIs.

You can check out this answer on details of how to add body and headers to a post request: Fetch: POST json data

ayushgp
  • 4,891
  • 8
  • 40
  • 75