- sql-server
- 出现错误,与 'wss://website.azurewebsites.net:8080/ws' 的 WebSocket 连接失败:从 React 向 Azure SQL 服务器发出 POST 请求时
出现错误,与 'wss://website.azurewebsites.net:8080/ws' 的 WebSocket 连接失败:从 React 向 Azure SQL 服务器发出 POST 请求时
当我尝试将数据添加到我的 SQL 数据库时,我的 Azure Web 应用程序(Linux)出现问题,以下是我收到的错误:DataAdd.js:26 POST https://website.azurewebsites.net:5000/add-data...
我在尝试将数据添加到我的 sql 数据库时遇到了 Azure Web 应用程序(Linux)的问题
以下是我遇到的错误:
DataAdd.js:26
POST https://website.azurewebsites.net:5000/add-data net::ERR_CONNECTION_TIMED_OUT
Error: TypeError: Failed to fetch
at handleSubmit (DataAdd.js:26:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1)
at executeDispatch (react-dom.development.js:9041:1)
at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1)
at processDispatchQueue (react-dom.development.js:9086:1)
at dispatchEventsForPlugins (react-dom.development.js:9097:1)
at react-dom.development.js:9288:1
WebSocketClient.js:13 WebSocket connection to 'wss://website.azurewebsites.net:8080/ws' failed:
这是我的 DataAdd.js 代码:
import React, { useState } from 'react';
import './DataAdd.css';
const DataAdd = () => {
const [formData, setFormData] = useState({
description: '',
Nimi: '',
Syntymäaika: '',
Rotu: '',
Sukupuoli: '',
Rekisterinumero: '',
Omistaja: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch('https://website.azurewebsites.net:5000/add-data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
if (response.ok) {
alert('Data added successfully');
setFormData({
description: '',
Nimi: '',
Syntymäaika: '',
Rotu: '',
Sukupuoli: '',
Rekisterinumero: '',
Omistaja: ''
});
} else {
alert('Error adding data');
}
} catch (error) {
console.error('Error:', error);
alert('Error adding data');
}
};
return (
<div>
<h1>Add Data</h1>
<form onSubmit={handleSubmit}>
<div>
<label>Description</label>
<input type="text" name="description" value={formData.description} onChange={handleChange} required />
</div>
<div>
<label>Nimi</label>
<input type="text" name="Nimi" value={formData.Nimi} onChange={handleChange} required />
</div>
<div>
<label>Syntymäaika</label>
<input type="date" name="Syntymäaika" value={formData.Syntymäaika} onChange={handleChange} required />
</div>
<div>
<label>Rotu</label>
<input type="text" name="Rotu" value={formData.Rotu} onChange={handleChange} required />
</div>
<div>
<label>Sukupuoli</label>
<input type="text" name="Sukupuoli" value={formData.Sukupuoli} onChange={handleChange} required />
</div>
<div>
<label>Rekisterinumero</label>
<input type="text" name="Rekisterinumero" value={formData.Rekisterinumero} onChange={handleChange} required />
</div>
<div>
<label>Omistaja</label>
<input type="text" name="Omistaja" value={formData.Omistaja} onChange={handleChange} required />
</div>
<button type="submit">Add Data</button>
</form>
</div>
);
};
export default DataAdd;
这是我的 server.js 代码:
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const sql = require('mssql');
const app = express();
const port = process.env.REACT_APP_AZURE_SERVER_PORT;
const config = {
user: process.env.REACT_APP_AZURE_SQL_USER,
password: process.env.REACT_APP_AZURE_SQL_PASSWORD,
server: process.env.REACT_APP_AZURE_SQL_SERVER,
port: parseInt(process.env.REACT_APP_AZURE_SQL_PORT, 10),
database: process.env.REACT_APP_AZURE_SQL_DATABASE,
authentication: {
type: 'default'
},
options: {
encrypt: true,
requestTimeout: 60000,
connectionTimeout: 30000
}
};
// Add CORS middleware
app.use(cors({
origin: 'https://website.azurewebsites.net', // Adjust based on your frontend URL
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
preflightContinue: false,
optionsSuccessStatus: 204
}));
// Add body parser middleware
app.use(express.json());
async function connectWithRetry() {
let retries = 5;
while (retries) {
try {
const pool = await sql.connect(config);
return pool;
} catch (err) {
console.log(`Connection failed, retries left: ${retries - 1}`);
console.error(err);
retries -= 1;
await new Promise(res => setTimeout(res, 5000)); // wait for 5 seconds before retrying
}
}
throw new Error('Could not connect to the database after multiple attempts');
}
connectWithRetry().then(pool => {
console.log("Connected to the database");
app.post('/add-data', async (req, res) => {
try {
console.log('Received request:', req.body);
const { description, Nimi, Syntymäaika, Rotu, Sukupuoli, Rekisterinumero, Omistaja } = req.body;
console.log('Connecting to database...');
const result = await pool.request()
.input('description', sql.NVarChar, description)
.input('Nimi', sql.NVarChar, Nimi)
.input('Syntymäaika', sql.Date, Syntymäaika)
.input('Rotu', sql.NVarChar, Rotu)
.input('Sukupuoli', sql.NVarChar, Sukupuoli)
.input('Rekisterinumero', sql.NVarChar, Rekisterinumero)
.input('Omistaja', sql.NVarChar, Omistaja)
.query(`
INSERT INTO dbo.hevoset (description, Nimi, Syntymäaika, Rotu, Sukupuoli, Rekisterinumero, Omistaja)
VALUES (@description, @Nimi, @Syntymäaika, @Rotu, @Sukupuoli, @Rekisterinumero, @Omistaja)
`);
console.log('Data added:', result);
res.status(200).send('Data added successfully');
} catch (err) {
console.error('Error adding data:', err);
res.status(500).send('Error adding data');
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
}).catch(err => {
console.error('Database connection failed: ', err.message);
});
我已经尝试过:已验证的服务器正在运行:服务器正在运行并且日志表明它正在监听正确的端口。
检查 URL 和端口:确保 React fetch 调用中的 URL 和端口与服务器的 URL 和端口匹配。
配置的 CORS:设置 CORS 选项以允许来自客户端 URL 的请求。
使用 curl/Postman 测试端点:从 curl/Postman 直接向服务器端点发出请求没有任何问题。
在本地进行了测试,数据库连接正常,添加数据也正常。
添加日志记录:添加日志记录以捕获传入的请求和错误。
我的期望:我希望 React 应用程序发出的 POST 请求能够成功到达 SQL Server,从而将数据添加到 Azure SQL 数据库。
环境:客户端:托管在 Azure (Linux) 上的 React Web 应用程序服务器:托管在 Azure 上的 SQL 服务器数据库:Azure 上的 SQL 数据库
下载声明: 本站所有软件和资料均为软件作者提供或网友推荐发布而来,仅供学习和研究使用,不得用于任何商业用途。如本站不慎侵犯你的版权请联系我,我将及时处理,并撤下相关内容!
-
引用 3楼
所以我只是使用 react + express js + mongodb 制作一个普通的用户注册表,并且我遇到了一个问题,如果我第一次尝试注册用户,它可以正常工作但是......
所以我只是使用 react + express js + mongodb 制作了一个普通的用户注册表单,并且我遇到了一个问题,如果我第一次尝试注册用户,它会正常工作,但如果我尝试添加另一个用户,它会给我错误 11000 前端代码的结构是这样的:有三个组件文件:注册表单,基本信息,Part1Signup Form.js
// Signup form .js import React, { useState } from 'react'; import axios from 'axios'; import BasicInfo from './Signup/BasicInfo'; const SignupForm = () => { const sendRequest = async (values) => { try { const response = await axios.post('http://localhost:5000/', values); console.log(response.data); } catch (error) { console.error(error); } }; return ( <div> <BasicInfo onComplete={sendRequest} /> </div> ); }; export default SignupForm;
Basic Info.js import React, { useState } from 'react'; import Part1 from './Part1'; const BasicInfo = ({onComplete}) => { const [formData, setFormData] = useState({ username: '', email: '', password: '', }) const handleUserInput = (e) => { setFormData({...formData, [e.target.name]: e.target.value}) } // when will this onComplete function be triggered? /* on the click of the submit button i will check if the whole form is complete or not if yes then the oncomplete function will be triggered next task is to get the data in basicinfostructure error 11000 is occuring, for data redundancy, i need to clear the data */ const checkSubmit = (e) => { e.preventDefault(); // Check if all fields are filled if (formData.username && formData.email && formData.password) { onComplete(formData); } else { alert('Please complete all fields'); } }; return ( <div name='basicInfo'> <Part1 formData={formData} handleUserInput={handleUserInput} /> <button type='submit' onClick={checkSubmit}>Submit</button> </div> ) } export default BasicInfo;
// Part1 import React from 'react'; const Part1 = ({ formData, handleUserInput }) => { return ( <form> <label>Username</label> <input type='text' name='username' value={formData.username} onChange={handleUserInput} /> <br /> <label>Email Address</label> <input type='email' name='email' value={formData.email} onChange={handleUserInput} /> <br /> <label>Password</label> <input type='password' name='password' value={formData.password} onChange={handleUserInput} /> <br /> </form> ); }; export default Part1;
请忽略我代码中的注释,那只是我写下自己的想法 XD,另外这应该是一个多步骤注册表单,但我现在只制作了第一部分,它不起作用
这里还有后端服务器代码const express = require('express'); const cors = require('cors'); const app = express(); app.use(express.json()); app.use(cors()); const User = require('./model/user'); require('./db/connection'); app.post('/', async(req, res) => { let user = new User(req.body); let result = await user.save(); res.send(result); }) app.listen(5000, ()=>{console.log('Server started at port 5000')});
throw new error_1.MongoServerError(res.writeErrors[0]); ^ MongoServerError: E11000 duplicate key error collection: new-test.users index: basicInfo.username_1 dup key: { basicInfo.username: null } at InsertOneOperation.execute (C:\Users\aksha\OneDrive\Desktop\Practise Folder\New folder\New Authhh\node_modules\mongodb\lib\operations\insert.js:51:19) at process.processTicksAndRejections (node:internal/process/task_queues:95:5) at async executeOperation (C:\Users\aksha\OneDrive\Desktop\Practise Folder\New folder\New Authhh\node_modules\mongodb\lib\operations\execute_operation.js:136:16) at async Collection.insertOne (C:\Users\aksha\OneDrive\Desktop\Practise Folder\New folder\New Authhh\node_modules\mongodb\lib\collection.js:155:16) { errorResponse: { index: 0, code: 11000, errmsg: 'E11000 duplicate key error collection: new-test.users index: basicInfo.username_1 dup key: { basicInfo.username: null }', keyPattern: { 'basicInfo.username': 1 }, keyValue: { 'basicInfo.username': null } }, index: 0, code: 11000, keyPattern: { 'basicInfo.username': 1 }, keyValue: { 'basicInfo.username': null }, [Symbol(errorLabels)]: Set(0) {} }
我尝试过记录和其他操作,但没有什么帮助,所以这是我的最后手段,甚至聊天 gpt 也帮不上忙,请大家帮帮我