javascript - Fetch API 不会将登录信息发布到 PHP 脚本
问题描述
我正在尝试为 Web 应用程序创建一个登录页面,该页面使用 JavaScript 提取用户数据,然后使用 Fetch API 将数据发布到将检查数据库的登录 PHP 脚本。我的 fetch 请求返回错误,但适用于公共 URL。
JS 文件:if(document.querySelector('#btn-submit')) {
let frmLogin = document.querySelector('form');
//begin login process
function loginProcess() {
event.preventDefault();
const data = {
user: document.getElementById('user').value,
pass: document.getElementById('pass').value,
}
const options = {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
}
};
fetch('*url*', options)
.then(res => res.json())
.then(res => console.log(res));
}
}
我不断收到的错误是:我的 console.log(res) 的“SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的意外字符”。输出应该是输入,当我使用此 URL 时会打印出来:https ://jsonplaceholder.typicode.com/posts
但不是当我使用我的网站的 URL 时(不包括出于隐私目的)
解决方案
我认为您的发布工作有效,但您服务器的答案似乎不是 json,请尝试此操作以进行最终提取:
fetch('*url*', options)
.then(res => res.text()) // use text instead of json
.then(res => console.log(res));