I am new to MEAN Stack and have been developing some applications on Mean stack.But I am stuck with my app.post() method .The browser's console gives a 405 error saying that the method is not allowed.Please help me.
Here;s my code for server file in javascript
var app =express();
var mongoose =require('mongoose');
var bodyParser =require('body-parser');
var urlencodedparser=app.use(bodyParser.urlencoded({extended:false}));
var jsonParser = bodyParser.json()
app.get('/',function(request,response){
response.sendFile(__dirname+'/clients/views/index.html');
});
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
var port=process.env.PORT || 3000;
app.listen(port,function(){
console.log('Listening to the server at port '+port);
});
Based on the Application.post() Express documentation, I think you probably want to change the first line of your post listener from:
app.post('/api/meetups',jsonParser,function(req,res){
console.log(req.body);
});
To this:
app.post('/api/meetups',function(req,res){
console.log(req.body);
});
I don't think it takes the additional parameter you specified related to JSON parsing. If you need to parse JSON you may want to look into using body-parser with middleware like this (which you would put ABOVE the post listener):
var bodyParser = require('body-parser');
app.use(bodyParser.json());
Good luck!
Related
I am working on Salesforce and Slack integration. And I don't know much about javascript and its related technologies. Could you please look into the code and let me know whats missing?
// Import express and request moduless
var express = require('express');
var request = require('request');
var url = require('url');
var clientId = '****';
var clientSecret = '****';
var SF_LOGIN_URL = "http://login.salesforce.com";
var SF_CLIENT_ID = "****";
// We define the port we want to listen to. Logically this has to be the same port than we specified on ngrok.
const PORT=4390;
// Instantiates Express and assigns our app variable to it
var app = express();
app.enable('trust proxy');
//var server = http.createServer(app);
//Lets start our server
app.listen(PORT, function () {
//Callback triggered when server is successfully listening.
console.log("Example app listening on port " + PORT);
});
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
// Route the endpoint that our slash command will point to and send back a simple response to indicate that ngrok is working
app.post('/oauth', function(req, res) {
oauth(req, res);
});
function oauth(req, res){
res.redirect(200, `${SF_LOGIN_URL}/services/oauth2/authorize?response_type=code&client_id=${SF_CLIENT_ID}&redirect_uri=****/oauth&display=touch}`);
console.log(url.location.href);
}
It looks to me like you're redirecting an authorization request to Salesforce, and asking Salesforce.com (SFDC) to redirect it back to ****/oauth (from the redirect_uri= query parameter to the SFDC URL.
Are you hoping it will get redirected back to your own /oauth endpoint?
If so, it's possible SFDC is redirecting it with a GET operation rather than a POST operation. Be aware that the parameters to a GET show up in req.params rather than req.body.
Try implementing a get() handler to see if you get something workable.
app.get('/oauth', function(req, res) {
console.log ('GET /oauth', req.params)
/* do something here */
});
In very new to express js. I just wrote a simple program to send JSON request through postman and get the response.
Why I can't get any response? it always says could not get any response. I go through several tutorials and could not figure out what exact missing here?. Here is my code.
const express = require('express');
const app = express();
app.use(express.json);
app.post('/', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(3000, () =>{
console.log("Listen in port 30000");
});
I figure out what went wrong. Here
app.use(express.json);
Should be This,
app.use(express.json());
You have to parse your json data inorder to consume it.
check the following code.
install this package.
npm i body-parser
and use it with your express object as below
let bodyParser = require('body-parser')
app.use(bodyParser.json())
I found my question was asked a year ago here app.post() not working with Express but the code written there is outdated (the way bodyparser was added doesn't work anymore as well as function mentioned below) plus the asker never chose an answer so the question was never solved.
Here's my code
const express = require("express");
const db = require("mysql");
const app = express();
const bodyParser = require("body-parser");
const multer = require("multer"); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
const http = require("http");
const path = require("path");
app.set("view engine", "jade");
app.set("views", path.join(__dirname));
console.log("before");
app.listen(8000, () => {
console.log("Server started!");
console.log("within");
});
console.log("after");
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post("/", function(req, res) {
console.log("hit here in post");
res.render("index.jade", {});
console.log("hit here in post");
res.json({ name: "John" });
res.status(500).json({ error: "message" });
res.end();
});
app.get("/", function(req, res) {
res.render("index.jade", {});
console.log("hit here in get");
console.log(req.body);
});
Here's the output.
before
after
Server started!
within
hit here in get
{}
I even tried to wrap the app sets and uses in app.configure like the asker of the other question to see if that was the issue but that configure function doesn't seem to exist anymore because I got an error about it.
Also I should probably note. My routing here is correct. I haven't made a views subfolder yet so that's why I have it written as it is.
Update
I think I may have spotted the issue but I don't understand why it's occurring. In the network tab of the browser I see that GET is getting 404 error because of a favicon.ico request but I don't understand where that request is coming from. I've seen the serve-favicon npm module to support it but didn't want to added because I never intended to add a favicon image to my server. I don't even understand how that would work.
Reply to last comment by James
What do you mean by I configure the middleware after it has started? Are you referring to the fact that the post method is written after port listening has started? Also if that's the reason why post isn't executing how come the get method executes regardless of that? I'm not holding back any server code aside from code I currently have commented out for the moment but that code I posted is my main index.js file and it's the only file I modified from the standard npm init project. I haven't setup any routes because I don't see the need to do so (even when I add react since my project is simple in concept of communication between reactjs, nodejs and a database "hence my frustration") which is why I'm trying to have get and post only access the root directory.
favicon is automatically requested by the browser. it is the icon used in the browser tab or url address bar
Add this, before app.get():
app.all('/', function(req, res, next) {
console.log({method: req.method, url: req.url});
next();
});
In my NODEjs ( using Express ) application, I want to use Country Code inside routes.js but I am unable to access localstorage inside the routes.js
Please provide some solution.
LocalStorage is only available in browsers on the Window object.
The Window object is not available server side.
MDN
Following your comment, you could implement a route in your express application which takes the IP as part of the body.
For this to work you will need body-parser middleware. Example application:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server;
app.use(bodyParser.json());
app.get('/api/ip', function (req, res) {
res.send(req.body.ip);
});
server = app.listen(3000);
This would return the posted IP.
I'm having some troubles trying to stablish a REST API with nodeJS and express. The following code defines two routes, "stores" and "user".
Surprisingly, the route to "/user" is working nice but when a request arrives to "/stores" the request body appears undefined. I've searched for a solution but nothing seems to work for me.
Both controllers have the same structure.
What am I doing wrong?
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require('mongoose');
// Connection to DB
mongoose.connect('mongodb://localhost/appDB', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});
// Middlewares
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
//Import models and controllers
var userModel=require("./models/user.js")(app,mongoose);
var storeModel=require("./models/store.js")(app,mongoose);
var usersController=require("./controllers/users.js");
var storesController=require("./controllers/stores.js");
//Router options
var router=express.Router();
router.route('/stores')
.get(storesController.getNearestStores);
router.route('/user')
.post(usersController.addUser);
app.use(router);
//Start server
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
Thank you very much.
P.S.:First time with nodejs and express(and even mongo)
This is because there is no body on a GET request in the http standard. Only POST and PUT.
What you want to do instead is use a query string
get
/stores?location=mystore
this way on your callback you have access to req.query
req.query
{
location: 'mystore'
}
HTTP GET with request body
This gave me the solution, get requests don't accept parameters under HTTP standard.