0

I have problem i wrote simple API but when i want use method.I have information url: "http://localhost:4200/undefined/api/SaveUser" Can be a problems with routing? I dont know where is problem. I start node server and mongos. Did anyone have a similar problem?

code on my API

var express = require('express');
var path = require("path");
var bodyParser = require('body-parser');
var mongo = require('mongoose');
const port = process.env.PORT || 3000
var db = mongo.connect("mongodb://localhost:27017/crud", function(err, response){
    if(err) {console.log(err); }
    else { console.log("Connected to"+ db, " + ", response); }
});

var app = express();
app.use(bodyParser());
app.use(bodyParser.json({limit: '5mb'}));
app.use(bodyParser.urlencoded({extended:true}));

app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials',true);
    next();
});

var Schema = mongo.Schema;

var UserSchema = new Schema({
    name: { type: String },
    address: {type: String},
}, { versionKey: false});

var model = mongo.model('users', UserSchema, 'users');

app.post("/api/SaveUser", function(req, res) {
    var mod = new model(req, body);
    mod.save(function(err, data){
        if (err){
            res.send(err);
        } else {
            res.send({data: "Users save"});
        }
    });
});
3
  • share ur angular code snippet too Commented Dec 2, 2019 at 1:13
  • 1
    You're exposing port 3000 but make a call to port 4200. Commented Dec 2, 2019 at 1:13
  • See the "undefined" in your URL http://localhost:4200/undefined/api/SaveUser? That looks like you're programmatically constructing the URL and one of the variables you are using does not have a proper value. If that's the URL the client is requesting, then the problem is on the client, not the server Commented Dec 2, 2019 at 1:47

2 Answers 2

1

Set your env variable to 4200 if it not set. And if you are setting your URL programatically it can be a variable issue else it is error from the client side.

You can use postman to debug your api, routes, data etc.

Sign up to request clarification or add additional context in comments.

Comments

0

install POSTMAN to check your api is working proper or not

make post request to http://localhost:3000/api/SaveUser , http://localhost:4200/api/SaveUser if you are getting proper response than it is not server side issue ,

now you have to check your angular app

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.