我一直在使用Mean堆栈构建一个简单的博客应用程序,我似乎很挣扎,即使我在此处发送数据,但request.body始终为空,并且请求始终在Chrome网络标签中处于待处理状态,直到给出Err_connction_refused或类似的东西,请注意我将表单数据传递给问题所在的服务
注册服务
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class RegisterService {
constructor(private http: Http) { }
// A form data is passed as an argument to this function
register(user) {
let headers = new Headers();
headers.append("Content-Type", "multipart/form-data")
return this.http.post("http://localhost:3000/api/users/register", user, {headers})
.pipe(map(res => res.json()))
}
}
服务器端的路由(旁注:不必担心req.file.path)
// Registering a user
router.post("/register", upload.single("profileImage") , (req, res) => {
let newUser = new User({
username: req.body.username,
password: req.body.password,
email: req.body.email,
name: req.body.name,
bio: req.body.bio,
interests: req.body.interests,
profileImage: req.body.path
})
User.addUser(newUser, (err) => {
if (err) return err;
res.send({
success: "true",
msg: "You've logged in sucessfully"
})
})
})
答案 0 :(得分:2)
第一步ID
安装模块后,将以下代码添加到您的app.js
npm i body-parser
修改
使用的URL为 var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded())
app.use(bodyParser.urlencoded({
extended: true
}));
但是您的路线只有http://localhost:3000/api/users/register
。
您的路线和传递的URL应该匹配