【发布时间】:2019-12-02 01:08:34
【问题描述】:
我有问题,我编写了简单的 API,但是当我想要使用方法时。我有信息 url: "http://localhost:4200/undefined/api/SaveUser"
可能是路由问题?
我不知道问题出在哪里。我启动节点服务器和 mongos。
有没有人遇到过类似的问题?
我的 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"});
}
});
});
【问题讨论】:
-
也分享你的角码sn-p
-
你暴露了 3000 端口,但调用了 4200 端口。
-
在您的 URL
http://localhost:4200/undefined/api/SaveUser中看到“未定义”?看起来您正在以编程方式构建 URL,并且您使用的变量之一没有正确的值。如果这是客户端请求的 URL,那么问题出在客户端,而不是服务器
标签: javascript node.js angular mongodb