简单的.net关联Node.js服务器

客户端 C# .net

using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

public class ApiService
{
    private readonly HttpClient _httpClient;

    public ApiService()
    {
        _httpClient = new HttpClient { BaseAddress = new Uri("http://localhost:3000/") };
    }

	//简单的登陆方法
    public string Login(string username, string password)
    {
        var loginData = new
        {
            username,
            password
        };

        var content = new StringContent(JsonConvert.SerializeObject(loginData), Encoding.UTF8, "application/json");

        var response = _httpClient.PostAsync("login", content).Result;

        var responseString = response.Content.ReadAsStringAsync().Result;

        if (response.IsSuccessStatusCode)
        {
            return "Login successful: " + responseString;
        }
        else
        {
            return "Login failed: " + responseString;
        }
    }
}

using System;

public class Program
{
    public static void Main(string[] args)
    {
        var apiService = new ApiService();

        // 调用登录方法
        var loginResult = apiService.Login("yourUsername", "yourPassword");
        Console.WriteLine(loginResult);
}

服务端 Node.js

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

// 使用 body-parser 中间件解析 JSON 请求体
app.use(bodyParser.json());

// 处理登录请求
app.post('/login', (req, res) => {
  const { username, password } = req.body;

  // 在这里添加你的登录逻辑
  if (username === 'admin' && password === 'password') {
    res.json({ message: 'Login successful' });
  } else {
    res.status(401).json({ message: 'Invalid username or password' });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值