简体   繁体   中英

API Node.js + express, problem with request

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"});
        }
    });
});

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.

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

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