【发布时间】:2021-05-25 06:00:28
【问题描述】:
抱歉标题凌乱-我是网络开发新手,不知道如何最好地表达这一点。
我的目标
- 我想在我的 React.js 前端单击一个按钮,并让 C# 后端激活一个 GPIO 作为响应。
- 经过一番研究,我想使用 HTTP Post 功能,但不知道从哪里开始。
- 简单地说:我想从我的 React.js 前端调用一个 C# 函数
到目前为止我所拥有的:
- React.JS 文件:RoomComponent.js
import React, { Component } from 'react';
export class RoomComponent extends Component {
static displayName = RoomComponent.name;
constructor(props) {
super(props);
this.state = { lightOn: true };
this.turnOnLight = this.turnOnLight.bind(this);
}
componentDidMount() {
// call turn on light function, where HTTP post is used to send on signal to back-end
}
render() {
return (
<div>
<button className="btn btn-primary" onClick={this.turnOnLight}>Toggle LED</button>
</div>
);
}
async turnOnLight() {
// here i would use HTTP post with a "fetch" function? How do I send data here?
alert("LED toggled");
}
}
- C# 文件:Lighting.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Device.Gpio;
using System.Net.Http;
namespace control.Controllers
{
[ApiController]
[Route("[controller]")]
public class LightingController : ControllerBase
{
private readonly int ledPin = 11;
private GpioController controller = new GpioController();
private static readonly HttpClient client = new HttpClient();
[HttpPost]
public void turnOnLed()
{
// somehow recieve JSON with data telling the GPIO to turn on, and activate it accordingly
controller.Write(ledPin, PinValue.High);
}
public LightingController()
{
controller.OpenPin(ledPin, PinMode.Output);
}
}
}
我在哪里挣扎
我很难理解如何制定 HTTP Post 来与后端通信,我希望 GPIO 被激活。在线示例总是 HTTP 从远程 URL 发布/获取信息,但对我来说,它们都包含在同一个应用程序中。我将非常感谢任何与此相关的建议或指导,甚至是其他资源,以帮助我更好地了解如何去做。
谢谢!
【问题讨论】:
-
在你的控制器中,在你的类下放 [RoutePrefix("api/Lighting")],在你上面的动作中放 [HttpPost, Route("YourActionName")]。在您的前端,像通常调用它一样调用您的 API
-
我通常如何称呼它?我对这一切真的很陌生。谢谢
标签: javascript c# asp.net reactjs