[英]Unexpected token '<', "<!DOCTYPE "... is not valid JSON. Utilizing express and parsing error. Any suggestions would be great
For the past few days, I have been attempting to solve this error.在过去的几天里,我一直在尝试解决这个错误。 I am extremely baffled, as I have no idea why this isn't working.我非常困惑,因为我不知道为什么这不起作用。 Any help or suggestions would be greatly appreciated.任何帮助或建议将不胜感激。
When I attempt to get data from node.js in my client side js, my JSON parser is giving me an error:当我尝试在我的客户端 js 中从 node.js 获取数据时,我的 JSON 解析器给我一个错误:
uncaught SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
at JSON.parse (<anonymous>)
at XMLHttpRequest.onLoad (something.js:18:29)
I am using node, js, and html for this, 3 files total.为此,我使用了 node、js 和 html,总共 3 个文件。 Here is the index.js:这是 index.js:
const express = require('express');
const app = express();
app.use(express.static('public'));
app.use(express.json());
app.listen(3000, () => {
console.log('server started');
});
app.get('/', function(req, res) {
console.log('hello')
});
app.listen(8080);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/testing/thisshit', async function(req, res) {
console.log(req.body);
var dataToSendToClient = '{"message":"potatohead"}';
res.send(dataToSendToClient);
});
The html: html:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>hellow world</div>
<script src="something.js"></script>
</body>
</html>
The client-side JS:客户端JS:
console.log('testing')
var abcd = {juice: "juice"}
$.post( '/testing/thisshit', abcd);
var res = new XMLHttpRequest();
var url = '/testing/thisshit';
res.open('GET',url,true); // set this to POST if you would like
res.addEventListener('load',onLoad);
res.addEventListener('error',onError);
res.send();
function onLoad() {
var response = this.responseText;
console.log(response);
var parsedResponse = JSON.parse(response);
console.log("the result: " + parsedResponse)
}
function onError() {
console.log('error');
}
No matter what I attempt, it seems to baffle me.无论我尝试什么,它似乎都让我感到困惑。 Any answers or suggestions would be incredibly helpful, and thank you in advance for any suggestions.任何答案或建议都将非常有帮助,并提前感谢您提出任何建议。
Oh wow.哦哇。 hahaha my bad.哈哈哈我的错。 After 10 hours of a gruelling search trying to solve this, I finally solved this.经过 10 个小时的艰苦搜索试图解决这个问题,我终于解决了这个问题。
res.open('get')
was supposed to be res.open('post')
. res.open('get')
应该是res.open('post')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.