gpt4 book ai didi

javascript - 为什么我的 JavaScript 会抛出““No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?

转载 作者:行者123 更新时间:2023-12-03 01:31:22 26 4
gpt4 key购买 nike

问题我在node.js中构建了服务器端,并在Angular中构建了客户端,并创建了API POST和GET,请向我展示Cors问题

这是客户端 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"
});
});

问题向我显示了这条消息:请求的资源上不存在“Access-Control-Allow-Origin” header ”错误。

最佳答案

发生这种情况是因为 Postman 没有发送检查 Cors 策略的 Option 请求。 More information here .

您可以使用 Express 中的 CORS 来启用它。

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"
});
});

关于javascript - 为什么我的 JavaScript 会抛出““No ' Access-Control-Allow-Origin' header is present on the requested resources”错误,而 Postman 却没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51280564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com