Wednesday 24 May 2017

How to make a POST request when using rest api and client using express?

I'm having struggle with making POST request to my rest api. I tried with Postman and it works but through code I am getting error. So I am running my rest api on localhost:3000 and my react app on localhost:8080. So here's a running scripts:

"scripts": {
"start": "webpack-dev-server --open",
"build": "NODE_ENV='production' webpack -p",
"build:prod": "webpack -p",
"deploy": "npm run build && firebase deploy",
"firebase-init": "firebase login && firebase init",
"server": "nodemon index.js",
"dev":"concurrently \"npm run start\" \"npm run server\""


},

and i am running my app with npm run dev. Now my server.js(index.js in my case) looks like this:

const express = require("express");
const routes = require("./routes/api"); 
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const app = express();

mongoose.connect("mongodb://localhost/blog");
mongoose.Promise = global.Promise;

app.use(express.static("src"));
app.use(bodyParser.json());

app.use("/api", routes);

app.use(function (err, req, res, next) {
    res.status(422).send({error: err.message});
});
var PORT = 3000;
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}  
app.use(allowCrossDomain);  
app.listen(process.env.port || PORT, function () {
    console.log("Now listening for requests on localhost:"+PORT);
    console.log(process.env.PORT);
})

and my api.js looks like

const express = require("express");
const router = express.Router();
const Post = require("../models/post");  

router.get("/posts", function (req, res, next) {
    Post.find({})
        .then(function (posts) {
            res.send(posts);
        });
});
router.post("/posts", function (req, res, next) {
    Post.create(req.body)
        .then(function (post) {
            res.send(post);
        }).catch(next);
        console.log(req.url);
});
module.exports = router;

Finally my function looks like this

handleAdd(){
    var dataaa = {"text":"This is my first post!"}
$.ajax({ 
    type:"POST",
    url:" http://localhost:3000/api/posts",
    data: JSON.stringify(dataaa), 
    contentType: 'application/json',
    success: function(res) {
        console.log(res);
        console.log("Added");
    }.bind(this),
    error: function(xhr, status, err) {
        console.error(url, status, err.toString());
    }.bind(this)
}); 
}

I am getting error http://localhost:3000/api/posts 422 (Unprocessable Entity) and i am stuck here almost 3 days... So how to make that these two ports 3000 and 8080 communicate, so i can work normaly? Can anyone help me?



via Ivan

No comments:

Post a Comment