我是angular的初学者,我已经建立了一个简单的angular项目,试图在浏览器中调用方法。但是路由器文件中提到的方法没有从组件类型脚本文件中调用并显示错误,即 在Google Chrome和Firefox浏览器中 GET http://localhost:3000/User/register net :: ERR_CONNECTION_REFUSED ,它显示跨源请求已被阻止:同源策略禁止读取{{3}处的远程资源}。 (原因:CORS请求未成功)。。请帮助我解决此问题。下面我附上了我的代码,请检查。
**login.component.html FILE**
<p>login works!</p>
<form #userEntryForm="ngForm" (ngSubmit)="getEntry(userEntryForm.value)">
<table>
<tr>
<td colspan="2">
<button type="submit" class="btn btn-success">Get Value</button>
</td>
</tr>
<div>{{showMsg}}</div>
</table>
</form>
---------------------------------------------------------------
**login.component.ts FILE**
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { from } from 'rxjs';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor( private http: HttpClient ) { }
ngOnInit() {
}
getEntry(formData):void{
this.http.get("http://localhost:3000/User/register").subscribe(
res=>{
console.log(res);
}
);
}
}
-------------------------------------------------------------
**Server.js file**
var express = require('express');
var cors = require('cors');
var bodyParser = require("body-parser");
var app = express()
var port = process.env.PORT || 3000
app.use(bodyParser.json());
app.use(cors());
app.use(
bodyParser.urlencoded({extended:false})
);
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.header('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
var Users = require("./src/routes/Users"); //./src/app/routes/Users
app.use("/users", Users);
app.listen(port,function(){
console.log("Server is running on port "+port);
**Router file(User.js)**
const express = require('express')
const users = express.Router()
const cors = require("cors")
const jwt = require("jsonwebtoken")
//const bcrypt = require('bcrypt')
var app = express()
//const User = require
users.use(cors())
var dboper = require('../app/dbconfig/dboperation');
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.header('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
users.get('/register', function (req, res, next) {
console.log("rows");
dboper.register(function (err, rows) {
if (err) {
console.log(rows,"errer");
res.json(err);
}
else {
console.log(rows,"ef3refr3r");
res.json(rows);
}
});
});
module.exports = users
----------------------------------------------------------
**package.json file**
{
"name": "firstapp",
"version": "0.0.0",
"main": "server.js",
"scripts": {
"dev": "nodemon server.js",
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~8.2.14",
"@angular/common": "~8.2.14",
"@angular/compiler": "~8.2.14",
"@angular/core": "~8.2.14",
"@angular/forms": "~8.2.14",
"@angular/platform-browser": "~8.2.14",
"@angular/platform-browser-dynamic": "~8.2.14",
"@angular/router": "~8.2.14",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"mysql": "^2.17.1",
"nodemon": "^2.0.2",
"rxjs": "~6.4.0",
"tslib": "^1.10.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.803.22",
"@angular/cli": "~8.3.22",
"@angular/compiler-cli": "~8.2.14",
"@angular/language-service": "~8.2.14",
"@types/node": "~8.9.4",
"@types/jasmine": "~3.3.8",
"@types/jasminewd2": "~2.0.3",
"codelyzer": "^5.0.0",
"jasmine-core": "~3.4.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.1.0",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.1",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-node": "~7.0.0",
"tslint": "~5.15.0",
"typescript": "~3.5.3"
}
}