info: Microsoft.Hosting.Lifetime[14]
Now listeningon: https://localhost:7240
info: Microsoft.Hosting.Lifetime[14]
Now listeningon: http://localhost:5162
打开 Startup.cs 文件(或在 .NET 6+ 中直接修改 Program.cs),添加 CORS 配置:
var builder = WebApplication.CreateBuilder(args);// Add services to the container.
builder.Services.AddControllers();// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddCors(options =>{
options.AddPolicy("AllowAllOrigins",
builder =>{
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();});});var app = builder.Build();// Configure the HTTP request pipeline.if(app.Environment.IsDevelopment()){
app.UseSwagger();
app.UseSwaggerUI();}
app.UseHttpsRedirection();
app.UseCors("AllowAllOrigins");
app.UseAuthorization();
app.MapControllers();
app.Run();
创建前端项目(React.js)
安装 Node.js 和 npm :
如果还没有安装 Node.js,请前往 Node.js 官网 下载并安装。
创建 React 项目 :
打开终端或命令提示符,运行以下命令来创建一个新的 React 项目:
npx create-react-app frontend-demo
- 进入项目目录:
cd frontend-demo
安装 Axios (用于发送 HTTP 请求):
在项目目录中运行以下命令来安装 Axios:
npminstall axios
修改 React 代码 :
打开 src/App.js 文件,并修改为以下内容:
import logo from './logo.svg';
import './App.css';import React,{ useEffect, useState } from 'react';
import axios from 'axios';functionApp(){const[forecasts, setForecasts]=useState([]);useEffect(()=>{// 调用后端 API 获取数据,注意API的端口以及路由是否和后端的一致
axios.get('https://localhost:7240/api/weatherforecast').then(response =>{setForecasts(response.data);}).catch(error=>{
console.error('There was an error fetching the data!', error);});},[]);return(<div className="App"><h1>Weather Forecast</h1><ul>{forecasts.map((forecast, index)=>(<li key={index}>{forecast.date}-{forecast.summary}({forecast.temperatureC}°C)</li>))}</ul></div>);}
export default App;
运行前端项目 :
在终端中运行以下命令来启动 React 项目:
npm start
- React 应用将会在 http://localhost:3000 上运行,并且会从后端 API 获取天气预报数据。