0

the problem I have server-side build in node.js and client build in angular and create API POST and GET, put show me the Cors problem

this is client side angular

    import { Component, OnInit } from '@angular/core';
import { Http, Response  } from "@angular/http";
import { Router } from '@angular/router';
import { HttpClient , HttpClientModule , HttpHeaders } from '@angular/common/http';





@Component({
  selector: 'app-root',
  templateUrl: './app.login.html',
  styleUrls: ['./app.login.css'],
})
export class AppComponent  {
  title = 'app';

  constructor(private http: Http){
   this.LogIn();
   this.ping();
   
  }

  LogIn() {
    return this.http.post("localhost:3000/api/login/checklogin",  {
      username: 'mohsen',
      password: '2345'

    })
    .subscribe(
      res => {
        console.log(res.json());
      },
      err => {
        console.log("Error occured")
      }
    );
  }

const express = require('express');
const router = express.Router();

var app = express();

const listUsers = [
    {"username" : "wael", "password" : "1234"},
    {"username" : "mohsen", "password" : "2345"}
];


router.get('/ping.json' ,(req, res, next) => {
    res.status(200).json({
        message: 'pong'
    });
});

// router.post('/checklogin',(req, res ,next) =>{
router.post('/checklogin',(req, res ,next) =>{
    console.log(req.body);

    for(let i =0 ; i <listUsers.length ; i ++){
        console.log(listUsers[i]);
        if(listUsers[i].username === req.body.username && listUsers[i].password === req.body.password){
            res.status(200).json({
                message: "Success"
            });
            return;
        }
    }
    // not found
    res.status(200).json({
        message: "Failed"
    });
});

the problem shows me this message No 'Access-Control-Allow-Origin' header is present on the requested resource” error.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Mohsen
  • 11
  • 7
  • 1
    Because the [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) applies to browser-hosted code, and not to Postman. See the linked questions' answers for more details. – T.J. Crowder Jul 11 '18 at 08:27

2 Answers2

1

This is happening because Postman doesn't send an Option request, that checks Cors policies. More information here.

You can use CORS from Express for enabling it.

const express = require('express');
const router = express.Router();
var cors = require('cors');

var app = express();

app.use(cors())

const listUsers = [
    {"username" : "wael", "password" : "1234"},
    {"username" : "mohsen", "password" : "2345"}
];


router.get('/ping.json' ,(req, res, next) => {
    res.status(200).json({
        message: 'pong'
    });
});

// router.post('/checklogin',(req, res ,next) =>{
router.post('/checklogin',(req, res ,next) =>{
    console.log(req.body);

    for(let i =0 ; i <listUsers.length ; i ++){
        console.log(listUsers[i]);
        if(listUsers[i].username === req.body.username && listUsers[i].password === req.body.password){
            res.status(200).json({
                message: "Success"
            });
            return;
        }
    }
    // not found
    res.status(200).json({
        message: "Failed"
    });
});
Zooly
  • 4,736
  • 4
  • 34
  • 54
  • Even if Postman would send the `OPTIONS` request, it is allowed to totally ignore whatever comes back. The policy applies to web browsers only, the intention of the policy is to restrict the possibly malicious javascript that somehow got into your browser from the web but would misuse the publicly exposed APIs. The policy doesn't apply to non-browser apps, including desktop apps or web apps that run at the server. – Wiktor Zychla Jul 11 '18 at 08:53
  • now work in Postman Put the client side not work ,, this the message { Failed to load localhost:3000/api/login/checklogin: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. },,, AngualrJs – Mohsen Jul 11 '18 at 09:49
0

Because Postman is a development tool and not a browser. CORS issues are related to browsers and domains.

Ali Rida
  • 336
  • 2
  • 10