我尝试向MongoDB发出POST请求
首先我在Angular中使用服务
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpClientModule } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class RequestService {
constructor(private http: HttpClient) { }
postTask(task) {
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post('http://localhost:3000/tasks', task, {
headers: headers});
}
}
在像这样的组件中使用它:
postData(data) {
this.service.postTask(data).subscribe( (res) => {
console.log(data);
});
}
console.log给了我一个字符串。
问题在于,当我尝试发布数据时,我无法传递必须发布的req.body,参数。 console.log(req.body)为我返回{} 如果我传递像'test3'这样的字符串(现在就是示例),请求将被发布。我怎么能传递参数(req.body)?
以下是我将其发布到DB
的方式const app = express();
//Middleware for CORS
app.use(cors());
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
var todoSchema = new Schema({
taskName: String,
createdAt: Date,
isDone: Boolean,
prioraty: String
}, {
collection: 'tasks'
});
var Model = mongoose.model('Model', todoSchema);
mongoose.connect('mongodb://localhost:27017/admin').then(() => {
console.log("connected");
}).catch (() => {
console.log("not connected");
});
mongoose.connection.once('open', function () {
console.log('mongodb connected.');
});
//Save Task
app.post('/tasks', function(req, res) {
console.log("Here is req2", req.body);
var savedata = new Model({
'taskName': 'test3',
'isDone': false,
'createdAt': Date.now(),
'prioraty': 'medium'
}).save(function (err, result) {
if (err) throw err;
if (result) {
res.json(result)
}
})
});
PS。在控制台中,有效负载在这里,所以它应该工作..