javascript - Node JS sending data via URL

226

Recently i started programming with Node JS and found it an amazing replacement for php . In php i used to send get requests with Data in the url .

Something like : http://sample.com/public.php?x=helloworld

How to perform something like this in Node JS or is there a better way to send data to node unlike using the url in the above case .

Also , I have noticed that in some cases like stackoverflow , queries are different and dont include the file name

like /public?= instead of /public.php?=

How is this achieved , i always thought this was something related to REST . Also , if you have the answer you might as well guide me if it could be done with Node and a few sources to learn could be of help too .

414

Answer

Solution:

the most regular way to use REST api

req.query

// GET /search?q=foo+bar  
req.query.q  
// => "foo bar"  

// GET /phone?order=desc&phone[color]=black&shoe[type]=apple  
req.query.order  
// => "desc"  

req.query.phone.color  
// => "black"  

req.params

// GET /user/william  
req.params.name  
// => "william" 

req.body(for form data)

// POST /login
req.body.username
// => "william"
req.body.password
// => "xxxxxx"
39

Answer

Solution:

You'll probably be much better off using a pre-existing module as your web server. You can set one up manually, but you have to know about a lot of potential edge cases and really understand web servers. Most people in node use express. In node, as in any server-side language, you can pass data around in a few ways. The query string is one. You can also put some parameters directly in the url (like "/users/12" where 12 is a user id). Depending on the type of request, you can put data in the body of the request. You can also pass cookies. These are not node-specific. Explaining how express works in a post like this would be crazy, so I'll just give you a short example of a what a route handler matching your example route might look like:

var express = require('express');
var app = express();

app.get('/public', function(req, res, next) {
  // Get the value from the query string. Express makes the query
  // available as an object on the request parameter.
  var x = req.query.x;

  // Execute your main logic
  doSomethingWithX(x);

  // Send a response
  res.status(200).json({ foo: 'bar' });
});

People are also looking for solutions to the problem: PHP variable declarations or function "recall"

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.