【问题标题】:Sending POST request via Observable from angular to nodejs通过 Observable 从 Angular 向 nodejs 发送 POST 请求
【发布时间】:2018-05-04 15:26:04
【问题描述】:

我有一个 Angular 5 应用程序正在运行并将 ExpressJs 配置为后端,我在尝试订阅 Angular 中的 observable 时遇到了问题。我的 Angular 应用程序在 localhost:4200 上运行,而我的 NodeJs 应用程序是在 localhost:3000 上运行。我可以很好地从角度向节点发送 GET 请求,但是当我尝试发送带有一些数据的 POST 请求时,我在 Chrome 开发工具中收到此错误:

无法加载 localhost:3000/user:跨域请求仅支持协议方案:http、data、chrome、chrome-extension、https。

似乎 Angular 甚至没有发送请求,因为我在终端中看不到任何活动。我还尝试在终端中使用 curl 向我的 Node 应用程序发送 POST 请求,它似乎可以正常工作,所以我认为这不是 CORS 问题,而是我的角度代码有问题。 这是我的代码: 角服务:

@Injectable()
export class AuthService {
    constructor(private http: Http){}

       register(user: User) {
           const body = JSON.stringify(user);
           const headers = new Headers({ 'content-Type': 
           'application/json'});
           return this.http.post('localhost:3000/user/register', body, {headers: headers})
                    .map((response: Response) => response.json())
                    .catch((error: Response) => Observable.throw(error.json()));

    }

}

角度组件:

onSubmit() {
    const user = new User(this.registrationForm.value.email,
                            this.registrationForm.value.password,
                            this.registrationForm.value.firstName,
                            this.registrationForm.value.lastName);
    this.authService.register(user)
                    .subscribe(
                        data => console.log(data),
                        error => console.log(error)
                    );
    this.registrationForm.reset();
}

不确定这是否相关,但这是我针对此请求的后端代码:

router.post('/register', function(req,res,next){
    var user = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        password: bcrypt.hashSync(req.body.password, 10),
        email: req.body.email
    });
    user.save(function(err, result){
        if (err) {
            return res.status(500).json({
                title: 'Error while saving user',
                error: err
            });
        }
        res.status(201).json({
            message: 'User created',
            obj: result
        });
    });
});

我在 Node 中正确设置了我的标题:

app.options(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

感谢您提供的任何帮助!这真是让我头疼:(

【问题讨论】:

    标签: node.js angular express cors observable


    【解决方案1】:

    无法加载 localhost:3000/user:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

    您只是缺少请求 URL 中的 http: 协议部分。

    替换这个:

    return this.http.post('localhost:3000/user', body, {headers: headers})
    

    …用这个:

    return this.http.post('http://localhost:3000/user', body, {headers: headers})
    

    【讨论】:

      【解决方案2】:

      这可能是因为您将数据发布到 localhost:3000/user 并收听 /register..

          @Injectable()
              export class AuthService {
                  constructor(private http: Http){}
      
                     register(user: User) {
                         const body = JSON.stringify(user);
                         const headers = new Headers({ 'content-Type': 
                         'application/json'});
      
                        // 'localhost:3000/user' change this to http://localhost:3000/user/register
      
                         return this.http.post('localhost:3000/user', body, {headers: headers})
                                  .map((response: Response) => response.json())
                                  .catch((error: Response) => Observable.throw(error.json()));
      
                  }
      
              }
      

      【讨论】:

        猜你喜欢
        • 2018-02-20
        • 2019-05-13
        • 2014-07-28
        • 2018-02-22
        • 2011-06-10
        • 1970-01-01
        • 1970-01-01
        • 2018-09-13
        • 1970-01-01
        相关资源
        最近更新 更多