В настоящее время я создаю веб-приложение с полным стеком, используя React, PostgreSQL и node.js
Я могу получить данные node.js. Однако мне нужно подождать не менее 10 секунд, чтобы получить другие данные из моей базы данных. Когда я пытаюсь получить данные за 10 секунд, я получаю OST http://localhost: 3001 / api / search 400 (неверный запрос). Это странно, так как я не собираю и не вставляю большие данные, только одну строку.
Спасибо за помощь.
сервер. js
let pool = new pg.Pool({
port: 5432,
database: 'boost',
max: 10,
options: {
encrypt: true
}
});
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
pp.post('/api/search', function(request, response){
var search = request.body.search_info;
var search_values = ["%"+search+"%"];
pool.connect((err,db,done) => {
if(err){
return response.status(400).send(err);
}
else{
db.query("SELECT * FROM Users WHERE username LIKE $1", [...search_values], (err, table) => {
done();
if(err){
return response.status(400).send(err);
}
else{
db.end();
var result = [];
for(var i in table.rows){
result.push(table.rows[i].username);
}
response.status(201).send({value: result});
}
})
}
})
})
сторона реакции
checkSearchResult(event){
event.preventDefault();
let data = {
search_info: this.refs.searchInput.value,
}
var request = new Request('http://localhost:3001/api/search', {
method: 'POST',
headers: new Headers({ 'Content-Type' : 'application/json' }),
body: JSON.stringify(data)
});
fetch(request).then((response) => {
response.json().then((data) => {
console.log(data);
});
}).catch(function(err){
console.log(err);
})
}
сетевой заголовок
Request URL: http://localhost:3001/api/search
Request Method: POST
Status Code: 400 Bad Request
Remote Address: [::1]:3001
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Allow-Origin: http://localhost:3000
Connection: keep-alive
Content-Length: 2
Content-Type: application/json; charset=utf-8
Date: Mon, 09 Mar 2020 02:58:22 GMT
ETag: W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"
X-Powered-By: Express
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 22
content-type: application/json
Host: localhost:3001
Origin: http://localhost:3000
Referer: http://localhost:3000/profile
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Mobile Safari/537.36
{search_info: "test"}
search_info: "test"
Сетевой инициатор
checkSearchResult @ TopNavigator.js:76
handleKeyPress @ TopNavigator.js:45
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executeDispatch @ react-dom.development.js:389
executeDispatchesInOrder @ react-dom.development.js:414
executeDispatchesAndRelease @ react-dom.development.js:3278
executeDispatchesAndReleaseTopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedPluginEventsInBatch @ react-dom.development.js:3514
handleTopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21902
batchedEventUpdates @ react-dom.development.js:1060
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptToDispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11061
discreteUpdates$1 @ react-dom.development.js:21918
discreteUpdates @ react-dom.development.js:1071
dispatchDiscreteEvent @ react-dom.development.js:4168