简体   繁体   中英

app.get('') is not working in node js with query parameters

Iam trying to provide a new route for my conversation application where it should accept the parameters passed along with the route should be accepted and can be used in client side.But I couldnt figure out why basic .get() is not working ,where Iam unable to render the html.

'use strict';
var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
var bodyParser = require('body-parser');
var app = express();
app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());
app.get('/:id',function(req,res){
     var userid = req.params.id;
     var pid = req.query.pid;
     res.sendFile(__dirname,'/public/index.html');
});
module.exports = app;

On my localhost:3000 index file is getting loaded but for something like localhost:3000/3405?pid=CBM it is not loading.

Then I have a js file on client side which would require these two values id and pid.For now I just hardcoded.But how can I use these values to client side js file..Can someone help me how can I do this... Thanks

Updated :Adding my client side js file

var Api = (function() {
var messageEndpoint = '/api/message';
var emp = {
    "pid": "CBM",
    "id": "3405",};
return {
        sendRequest: sendRequest,
         modifytext: function(intent, text) {
            if (intent == "Hello") {
                console.log(text, "Inside intent");
                for (var key in emp) {
                    var tempKey = '{{' + key + '}}';
                    var tempValue = emp[key];
                    text = replace(text, tempKey, tempValue);
                    console.log("came back");
                }  
            }
            return text;
            console.log(text,"Final text");
        }
    };
    function replace(text, originalString, replaceText) {
        console.log("Reached replace functions", text, originalString, replaceText);
        if (replaceText)
            text = text.replace(originalString, replaceText);
        else
            text = text.replace(originalString, "");
        return text

    }
 }());

This is incorrect:

res.sendFile(__dirname,'/public/index.html');

It should be this:

res.sendFile(__dirname + '/public/index.html');

Or (a bit more robust):

const path = require('path');
...
res.sendFile(path.join(__dirname, 'public/index.html'));

As a side note: apparently, if you pass a directory name to res.sendFile() , it will send back a 404 response. Not sure that the rationale behind that is.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM