简体   繁体   English

API Node.js + express,请求有问题

[英]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?我有问题,我写了简单的 API,但是当我想使用方法时。我有信息url: "http://localhost:4200/undefined/api/SaveUser"可能是路由问题? I dont know where is problem.我不知道问题出在哪里。 I start node server and mongos.我启动节点服务器和 mongos。 Did anyone have a similar problem?有没有人有类似的问题?

code on my API我的 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.如果未设置,请将您的 env 变量设置为 4200。 And if you are setting your URL programatically it can be a variable issue else it is error from the client side.如果您以编程方式设置您的 URL,它可能是一个可变问题,否则它是来自客户端的错误。

You can use postman to debug your api, routes, data etc.您可以使用邮递员来调试您的 api、路由、数据等。

install POSTMAN to check your api is working proper or not安装POSTMAN以检查您的 api 是否正常工作

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 ,http://localhost:3000/api/SaveUser发出 post 请求, http://localhost:4200/api/SaveUser如果您得到正确的响应而不是服务器端问题,

now you have to check your angular app现在你必须检查你的角度应用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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