【问题标题】:API Node.js + express, problem with requestAPI Node.js + express,请求问题
【发布时间】: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


【解决方案1】:

如果未设置,请将您的环境变量设置为 4200。 如果您以编程方式设置 URL,则它可能是一个变量问题,否则它是来自客户端的错误。

您可以使用 postman 来调试您的 api、路由、数据等。

【讨论】:

    【解决方案2】:

    安装 POSTMAN 以检查您的 api 是否正常工作

    http://localhost:3000/api/SaveUser 发出发帖请求, http://localhost:4200/api/SaveUser 如果您得到正确的响应而不是服务器端问题,

    现在你必须检查你的 Angular 应用程序

    【讨论】:

      猜你喜欢
      • 2016-10-05
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 2021-12-23
      • 2013-12-22
      • 1970-01-01
      • 2019-11-06
      • 2012-03-23
      相关资源
      最近更新 更多