fetch

fetch 的基本用法

fetch(url)
.then((res) => {
    return res.json()
})
.then((data) => {
    console.log(data)
})
.catch((err) => {
    console.log(err)
})

使用fetch过程中出现的问题

1、 首先我用NodeJS写了一个简易的接口

const express = require('express')
const app = express()
const path = require('path')

app.use('/public', express.static(path.join(__dirname, '/public')))

app.get('/user',function(req, res){
    res.send('get user')
})

app.listen(3333, function(){
    console.log('listening at 3333')
})

2、 在html页面中发送请求之后发现报了如下错误


fetch1.png

找出原因发现是:这个报错一般是用字符串拼凑JSON,然后用JSON.parse()转化为对象时非常容易报的错误,尤其是在文本框中处理JSON涉及到双引号单引号的转义符

3、 修改服务端中的代码

const express = require('express')
const app = express()
const path = require('path')


app.use('/public', express.static(path.join(__dirname, '/public')))

app.get('/user',function(req, res){
    res.send(JSON.stringify('get user')) ///////
})

app.listen(3333, function(){
    console.log('listening at 3333')
})

4、 成功返回数据


fetch2.png

POST 请求

fetch(url, {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
    body: {}
})
.then((res) => {
    return res.json()
})
.then((data) => {
    console.log(data)
})
.catch((err) => {
    console.log(err)
})
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容